我是Haskell的新手,我无法弄清楚如何声明“数据”类型以及如何使用该类型初始化变量。我还想知道如何更改该变量的某些成员的值。对于exaple:
data Memory a = A
{ cameFrom :: Maybe Direction
, lastVal :: val
, visited :: [Direction]
}
Direction是一种包含N,S,E,W的数据类型 val是一个Type 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 [])
我该如何解决这个问题?
更新:这样做了,非常感谢,但现在我有另一个问题
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:再次,这对我帮助很大,非常感谢
另外,我还有另一个问题(很抱歉这么麻烦)
如何仅处理某种类型的元素 例如,如果我有
Type Cell = (Int, Int)
Type Direction = (Cell, Int)
如果我想将Cell变量与Direction变量的Cell元素进行比较,该怎么办?
答案 0 :(得分: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 :(得分: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}