[英]Haskell recursion stack overflow
我對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
編輯 :
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
我相信代碼是不言自明的,但是:如果x等於2,則除以2,否則3 * x +1。這是著名的Collatz問題的一部分。
函數應用程序比其他許多操作具有更高的優先級,因此foo 3 * x + 1
實際上是在調用foo 3
,然后將結果乘以x
並加1
,這看起來像是無限循環所在的位置。
將其更改為以下內容可以解決此問題:
| odd x = foo $ 3 * x + 1
| x `mod` 2 == 0 = foo $ x `div` 2
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.