2012-04-10 89 views
-1

我是Haskell的新手,我无法弄清楚如何声明“数据”类型以及如何使用该类型初始化变量。我也想知道如何更改该变量的某些成员的值。对于的exaple:Haskell中的数据初始化和数据成员更改

data Memory a = A 
    { cameFrom :: Maybe Direction 
    , lastVal :: val 
    , visited :: [Direction] 
    } 

方向是包含N,S,E的数据类型,W val为一个int类型

init :: Int -> a 
init n = ((Nothing) n []) gives me the following error: 


The function `Nothing' is applied to two arguments, 
but its type `Maybe a0' has none 
In the expression: ((Nothing) n []) 
In an equation for `init': init n = ((Nothing) n []) 

我怎样才能解决这个问题?

UPDATE:那做到了,非常感谢你,但现在我还有一个问题

move :: val -> [Direction] -> Memory -> Direction 
move s cs m | s < m.lastVal = m.cameFrom 
      | ... 

这给了我以下错误:

Couldn't match expected type `Int' with actual type `a0 -> c0' 
    Expected type: val 
     Actual type: a0 -> c0 
    In the second argument of `(<)', namely `m . lastVal' 
    In the expression: s < m . lastVal 

更新2:同样,这帮助我很多,非常感谢你

另外,我还有一个问题(对不起,是这样一个麻烦)

我如何ADRESS一种 例如只有一个元素,如果我有

Type Cell = (Int, Int) 
Type Direction = (Cell, Int) 

我该如何着手,如果我想要一个细胞变量比较方向可变的电池元件?

+0

你的意思'lastVal ::了',与'数据存储了'匹配? – dave4420 2012-04-10 16:40:32

+3

这些都是很基本的问题;你有没有阅读过关于记录和其他数据类型的部分? – 2012-04-10 18:24:01

回答

2

至于更新。语法

m.lastVal 

m.cameFrom 

是不是你想要的。而是

move s cs m | s < lastVal m = cameFrom m 

访问器只是函数,所以用在前缀形式。 Haskell中.用于命名空间分辨率(这是不是路径依赖的)和函数组合

(.) :: (b -> c) -> (a -> b) -> a -> c 
(.) f g x = f (g x) 
1

初始化:

init :: Int -> Memory Int 
init n = A {cameFrom = Nothing, lastVal = n, visited = []} 

要更改值:严格来说你不改变值,返回另一个不同的值,例如:

toGetBackTo :: Direction -> Memory a -> Memory a 
toGetBackTo dir memory = memory {cameFrom = Just dir, visited = dir : visited memory}