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. 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.
*This is Question 9 from Chapter 3 of "Real World Haskell" in case you're wondering.
You're binding the name twice. First in the pattern Point c d
than in the where
clause.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With