2015-02-09 45 views
0

嗯......当为任何大于3的整数求值时,为什么函数以无限循环结束?递归Haskell函数中的无限循环

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 

回答

5

看来,主要的问题是,你定义的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 
+0

哦....这很有道理。谢谢 – Julio 2015-02-09 20:32:30