gpt4 book ai didi

functional-programming - 奇怪的 Haskell/GHCi 问题

转载 作者:行者123 更新时间:2023-12-04 18:15:41 27 4
gpt4 key购买 nike

所以我有一些代码*,当取三点时,应该返回一个方向。我已经编写了这个解决方案,但是每次我尝试运行它时,都会导致 GHCi 卡住,所以我想知道我做错了什么。这是代码:

--chapter 3 question 9
data Point x y = Point x y deriving (Eq, Show)
data Vector x y = Vector x y deriving (Eq, Show)

sub (Point x y) (Point a b) = (Vector (x-a) (y-b))
dot (Vector x y) (Vector a b) = (x*a)+(y*b)
perp (Vector x y) = (Vector (-y) x)
mag (Vector x y) = sqrt (dot v v) where v = (Vector x y)

data Direction = LeftTurn | RightTurn | Straight | Reverse | Stop | Undefined
deriving (Eq, Show)
getDirection (Point a b) (Point c d) (Point e f)
| a/=c && b/=d && c==e && d==f = Stop
| a==c && b==d || c==e && d==f || e==a && f==b = Undefined
| d > 0 = LeftTurn
| d < 0 = RightTurn
| otherwise = Straight
where d = dot (sub p1 p0) (perp (sub p2 p1))
where p0 = (Point a b)
p1 = (Point c d)
p2 = (Point e f)

我看不到递归,所以我不明白它为什么会这样。到目前为止,Haskell 编译器一直非常直言不讳地告诉我何时我正在做一些愚蠢的事情,但这编译得很好。

*这是“Real World Haskell”第 3 章中的问题 9,以防您想知道。

最佳答案

您将名称绑定(bind)两次。模式中的第一个 Point c dwhere条款。

因此,如果您尝试访问 d受模式约束,您实际上指的是 d来自 where递归子句。

关于functional-programming - 奇怪的 Haskell/GHCi 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4129909/

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