递归 Haskell 函数中的无限循环
Infinite loop in recursive Haskell function
嗯...为什么这个函数在计算任何大于 3 的整数时会以无限循环结束?
smallestMultiple n = factors [2..n] where
factors [] = []
factors (h:xs) = h:(factors $ filter ((<)1) [div x h|x<-xs])
where
div x y
|x `mod` y ==0 = x `div` y
|otherwise = x
看来主要问题是你定义了本地版本的 div
:
div x y
| x `mod` y == 0 = x `div` y
| otherwise = x
由于 where
子句(以及 let
中的绑定)是递归的,因此第一个案例右侧的 div
指的是相同的 div
你在定义!您可以使用不同的名称来解决此问题,例如 div'
:
div' x y
| x `mod` y == 0 = x `div` y
| otherwise = x
嗯...为什么这个函数在计算任何大于 3 的整数时会以无限循环结束?
smallestMultiple n = factors [2..n] where
factors [] = []
factors (h:xs) = h:(factors $ filter ((<)1) [div x h|x<-xs])
where
div x y
|x `mod` y ==0 = x `div` y
|otherwise = x
看来主要问题是你定义了本地版本的 div
:
div x y
| x `mod` y == 0 = x `div` y
| otherwise = x
由于 where
子句(以及 let
中的绑定)是递归的,因此第一个案例右侧的 div
指的是相同的 div
你在定义!您可以使用不同的名称来解决此问题,例如 div'
:
div' x y
| x `mod` y == 0 = x `div` y
| otherwise = x