简体   繁体   English

Haskell函数不会终止

[英]Haskell function does not terminate

I´ve written a function in Haskell that takes three points in the plane, and checks if they´re on a straight line, or make a right or left turn. 我在Haskell中编写了一个函数,它在平面上占据了三个点,并检查它们是否在一条直线上,或是向右转还是向左转。

Here´s the code: 这是代码:

detDirection :: Point -> Point -> Point -> Direction

detDirection a@(Point (x1, y1)) b@(Point (x2, y2)) c

= if (collinear1 a b c)
     then Straight
     else let
            ab                  = Vector [x2 - x1, y2 - y1]
            angleAbX            = angle ab (Vector [1, 0])
            (Point (x1, y1))    = turnAtP a b angleAbX
            (Point (x2, y2))    = turnAtP a c angleAbX

          in if (y1 > y2)
               then Right
               else Left

I´ve tested collinear1 , angle , turnAtP in GHCi, and they all terminate immediately. 我在GHCi中测试了collinear1angleturnAtP ,它们都立即终止。 detDirection , however, keeps running forever. 然而, detDirection永远保持运行。

Can someone tell me where the problem here is? 谁能告诉我这里的问题在哪里?

In Haskell, let is a recursive binding, that is, you can refer to variables declared in the let expression in the defining expressions of the other variables. 在Haskell中, let是一个递归绑定,也就是说,您可以在其他变量的定义表达式中引用let表达式中声明的变量。 So, when you write 所以,当你写作

let
        ab                  = Vector [x2 - x1, y2 - y1]
        angleAbX            = angle ab (Vector [1, 0])
        (Point (x1, y1))    = turnAtP a b angleAbX
        (Point (x2, y2))    = turnAtP a c angleAbX

the x1 , x2 , y1 , and y2 on the first line do not refer to the function arguments but to the same names declared later on in the let expression. 第一行中的x1x2y1y2不是引用函数参数,而是引用稍后在let表达式中声明的相同名称。 Just change the two Point lines to bind some different variables, like 只需更改两条Point线即可绑定一些不同的变量,例如

        (Point (x3, y3))    = turnAtP a b angleAbX
        (Point (x4, y4))    = turnAtP a c angleAbX

and modify your later computation accordingly, and your infinite looping will go away. 并相应地修改你的后续计算,你的无限循环将消失。

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

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