Haskell函数模式匹配问题

时间:2009-09-01 22:50:48

标签: haskell

我正在做一些功课,虽然我有一些SML的经验,但Haskell有一些奇怪之处。考虑这个简单的功能:

type Pos = (Int, Int)
data Move = North | South | East | West
move :: Move -> Pos -> Pos
move North (x,y) = (x, y+1)
move South (x,y) = (x, y-1)
move East  (x,y) = (x+1, y)
move West  (x,y) = (x-1, y)

moves :: [Move] -> Pos -> Pos
moves (m:ms) (x,y) = moves ms (move m (x,y))
moves [] p = p

此代码有效。但是,如果我用简单的(x,y)换出p元组(我不使用它),它在调用时失败(声明当然可以正常工作):

moves :: [Move] -> Pos -> Pos
moves (m:ms) p = moves ms (move m p)
moves [] p = p

*Main> let p = (1,1) :: Pos
*Main> move [North, North] p

<interactive>:1:5:
    Couldn't match expected type `Move' against inferred type `[a]'
    In the first argument of `move', namely `[North, North]'
    In the expression: move [North, North] p
    In the definition of `it': it = move [North, North] p

这对我来说似乎很奇怪,因为第二个参数已经在定义中被输入为Pos,那么为什么这个chokes,只有在调用时呢?我正在使用ghci btw。

1 个答案:

答案 0 :(得分:5)

你在移动 s 电话结束时忘记了“s”,不是吗?

*Main> move [North, North] p