Haskell递归堆栈溢出

dim*_*im8 0 stack-overflow recursion haskell guard

我对Haskell很新,很抱歉这个问题.但是 - 如何摆脱无休止的递归而不是溢出.这是代码:

foo :: Integer -> Integer
foo x
    | x == 1         = 1
    | x <= 0         = error "negative number or zero"
    | odd x          = foo 3 * x + 1
    | x `mod` 2 == 0 = foo x `div` 2
    | otherwise      = x
Run Code Online (Sandbox Code Playgroud)

编辑:

foo :: Integer -> (Integer, Integer)
foo x
    | x == 1         = (1, z) 
    | x <= 0         = error "negative number or zero"
    | odd x          = foo  (3 * x + 1) . inc z
    | even x         = foo  (x `div` 2) . inc z
    | otherwise      = (x, z)
  where z = 0

inc :: Integer -> Integer
inc i = i + 1
Run Code Online (Sandbox Code Playgroud)

我相信代码是不言自明的,但是:如果x是偶数则将其除以2,否则为3*x + 1.这是着名的Collat​​z问题的一部分.

Jef*_*mes 5

函数应用程序具有比许多其他操作更高的优先级,因此foo 3 * x + 1实际上是调用foo 3,然后将结果乘以x并添加1,这看起来就像无限循环可能的位置.

将其更改为以下内容应该可以解决:

| odd x          = foo $ 3 * x + 1
| x `mod` 2 == 0 = foo $ x `div` 2
Run Code Online (Sandbox Code Playgroud)

  • 你也可以把它写成`f(3*x + 1)`.有关`$`的更长描述,请参阅[this post](http://stackoverflow.com/questions/940382/haskell-difference-between-dot-and-dollar-sign). (2认同)