gpt4 book ai didi

haskell - 不在范围 : data constructor `Movement'

转载 作者:行者123 更新时间:2023-12-01 21:49:21 27 4
gpt4 key购买 nike

我想做一个函数,根据传递的字母改变特定的值。 (这些基本上给出了方向:东,西......)

代码是:

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 不再是函数。不过,我还是宁愿避开 guard ,而使用

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)

关于haskell - 不在范围 : data constructor `Movement' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59734402/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com