简体   繁体   English

奇怪的Haskell / GHCi问题

[英]Strange Haskell/GHCi issue

So I have a bit of code*, that when taking three points, is supposed to return a direction. 所以我有一些代码*,当拿三分时,应该返回一个方向。 I've written this solution, but every time I try to run it, it causes the GHCi to freeze, so I'm wondering what I'm doing wrong. 我写过这个解决方案,但每次尝试运行它都会导致GHCi冻结,所以我想知道我做错了什么。 Here's the code: 这是代码:

--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)

There's no recursion that I can see, so I don't understand why it's behaving this way. 我看不到递归,所以我不明白它为什么会这样。 So far the Haskell compiler has been very vocal about telling me when I'm doing something dumb, but this compiles just fine. 到目前为止,Haskell编译器一直非常直言不讳地告诉我什么时候我正在做一些愚蠢的事情,但是编译得很好。

*This is Question 9 from Chapter 3 of "Real World Haskell" in case you're wondering. *如果您想知道,这是“真实世界Haskell”第3章的问题9。

You're binding the name twice. 你绑定了两次名字。 First in the pattern Point cd than in the where clause. 首先是模式中的Point cd不是where子句。

Thus if you're trying to access the d bound by the pattern, you're actually referring to the d from the where clause recursively. 因此,如果您尝试访问模式绑定的d ,则实际上是where递归地引用where子句中的d

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM