简体   繁体   English

Haskell递归堆栈溢出

[英]Haskell recursion stack overflow

I am pretty new to Haskell, so sorry for the question. 我对Haskell来说还很陌生,非常抱歉。 But - how to get rid of the endless recursion and not been overflown. 但是-如何摆脱无尽的递归而不会被溢出。 This is the code: 这是代码:

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

EDIT : 编辑

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

I believe that the code is self-explanatory, but yet : If x is even then divide it with 2 otherwise 3*x + 1. This is part of the famous Collatz problem. 我相信代码是不言自明的,但是:如果x等于2,则除以2,否则3 * x +1。这是著名的Collat​​z问题的一部分。

Function application has higher precedence than many other operations, so foo 3 * x + 1 is actually calling foo 3 , then multiplying that result by x and adding 1 , which looks like where your infinite loop might be. 函数应用程序比其他许多操作具有更高的优先级,因此foo 3 * x + 1实际上是在调用foo 3 ,然后将结果乘以x并加1 ,这看起来像是无限循环所在的位置。

Changing it to the following should fix that: 将其更改为以下内容可以解决此问题:

| odd x          = foo $ 3 * x + 1
| x `mod` 2 == 0 = foo $ x `div` 2

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

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