不在范围内:数据构造函数“运动”
Not in scope: data constructor `Movement'
我想做一个函数,根据传递的字母改变一定的值。 (这些基本都是给出方向:东,西.....)
密码是:
data Movement = N Int | S Int | E Int | W Int deriving (Eq, Show)
step :: Movement -> (Int, Int) -> (Int, Int)
step (Movement x h) (y, z)
| x == N = (y, z+h)
| x == S = (y, z-h)
| x == W = (y-h, z)
| x == E = (y+h, z)
一个例子:
step (N 1) (239, 578) == (239, 579)
step (S 1) (240, 578) == (240, 577)
step (W 1) (239, 578) == (238, 578)
step (E 1) (239, 577) == (240, 577)
step (N 61) (239, 578) == (239,639)
step (N 2) (-4, 0) == (-4, 2)
step (E 1) (-4, 0) == (-3, 0)
step (S (-61)) (239, 578) == (239,639)
我不断收到
Not in scope: data constructor `Movement'
错误信息。
Movement
是类型,不是值。你不能在模式中使用它。
另外,N
等构造函数都是函数,不能==
函数。
你需要改用模式匹配,忘记守卫。
step :: Movement -> (Int, Int) -> (Int, Int)
step (N h) (y,z) = ...
step (S h) (y,z) = ...
step (W h) (y,z) = ...
step (E h) (y,z) = ...
或者,重构您的类型:
data Direction = N | S | E | W deriving (Eq, Show)
data Movement = Movement Direction Int deriving (Eq, Show)
step :: Movement -> (Int, Int) -> (Int, Int)
step (Movement x h) (y,z)
| x == N = (y, z+h)
| x == S = (y, z-h)
| x == W = (y-h, z)
| x == E = (y+h, z)
现在您的代码可以运行了,因为 Movement
也是一个数据构造函数,并且 N
和 friends 不再是函数。不过,我还是更愿意避开守卫,并使用
step :: Movement -> (Int, Int) -> (Int, Int)
step (Movement N h) (y,z) = (y, z+h)
step (Movement S h) (y,z) = (y, z-h)
step (Movement W h) (y,z) = (y-h, z)
step (Movement E h) (y,z) = (y+h, z)
我想做一个函数,根据传递的字母改变一定的值。 (这些基本都是给出方向:东,西.....)
密码是:
data Movement = N Int | S Int | E Int | W Int deriving (Eq, Show)
step :: Movement -> (Int, Int) -> (Int, Int)
step (Movement x h) (y, z)
| x == N = (y, z+h)
| x == S = (y, z-h)
| x == W = (y-h, z)
| x == E = (y+h, z)
一个例子:
step (N 1) (239, 578) == (239, 579)
step (S 1) (240, 578) == (240, 577)
step (W 1) (239, 578) == (238, 578)
step (E 1) (239, 577) == (240, 577)
step (N 61) (239, 578) == (239,639)
step (N 2) (-4, 0) == (-4, 2)
step (E 1) (-4, 0) == (-3, 0)
step (S (-61)) (239, 578) == (239,639)
我不断收到
Not in scope: data constructor `Movement'
错误信息。
Movement
是类型,不是值。你不能在模式中使用它。
另外,N
等构造函数都是函数,不能==
函数。
你需要改用模式匹配,忘记守卫。
step :: Movement -> (Int, Int) -> (Int, Int)
step (N h) (y,z) = ...
step (S h) (y,z) = ...
step (W h) (y,z) = ...
step (E h) (y,z) = ...
或者,重构您的类型:
data Direction = N | S | E | W deriving (Eq, Show)
data Movement = Movement Direction Int deriving (Eq, Show)
step :: Movement -> (Int, Int) -> (Int, Int)
step (Movement x h) (y,z)
| x == N = (y, z+h)
| x == S = (y, z-h)
| x == W = (y-h, z)
| x == E = (y+h, z)
现在您的代码可以运行了,因为 Movement
也是一个数据构造函数,并且 N
和 friends 不再是函数。不过,我还是更愿意避开守卫,并使用
step :: Movement -> (Int, Int) -> (Int, Int)
step (Movement N h) (y,z) = (y, z+h)
step (Movement S h) (y,z) = (y, z-h)
step (Movement W h) (y,z) = (y-h, z)
step (Movement E h) (y,z) = (y+h, z)