Haskell数据类型错误

时间:2012-04-14 18:40:31

标签: haskell types

我有这个功能:

data Memory = Memory
    {visited::[Point]
    ,dfsstack::[Point]
    ,currentPoz::Point
    }deriving(Eq)
perceiveAndAct :: SVal -> [Cardinal] -> a -> (Action, a)
perceiveAndAct s cs m
  | elem W cs == True && elem N cs == True && elem E cs == True && elem S cs == False = (Just S, Memory (visited m) (dfsstack m) (currentPoz m))

将m而不是Memory (visited m) (dfsstack m) (currentPoz m)设置正常,否则它会给我:

Couldn't match expected type `(a, b)'
           against inferred type `Memory -> Point'
    In the first argument of `fst', namely `currentPoz'
    In the first argument of `($)', namely `fst currentPoz'
    In the expression: fst currentPoz $ currentPoz m

可能是什么问题?

2 个答案:

答案 0 :(得分:5)

您提供的类型perceiveAndAct非常多态。比较:

id :: a -> a
id m = m -- the only correct implementation
id m = Memory (visited m) (dfsstack m) (currentPoz m) -- type error
-- only works for Memory, not all possible a

idMemory :: Memory -> Memory
id m = m -- this is fine
id m = Memory (visited m) (dfsstack m) (currentPoz m) -- also correct

但是,我有点困惑,因为您粘贴的类型错误与我在您声明您所做的更改时获得的类型错误不符。也许你最好粘贴你使用的确切代码,它会产生错误以及你得到的确切错误,而不是正确的代码和我们看不到的一些不可见代码的错误。

答案 1 :(得分:-1)

visiteddfsstackcurrentPoz是函数,它们不构造列表。

您想要编写Memory [m] [m] m,而不是。

visiteddfsstackcurrentPoz给予 someData :: Memory的功能,可以提取每个元素。

您还需要将perceiveAndAct的参数“m”的类型从:: a更改为:: Point