【发布时间】:2019-04-15 00:38:44
【问题描述】:
我需要计算一个名为happy 的函数的递归调用。我得到了一个提示,我可以用一个辅助功能来做到这一点。我只是想不通,我应该如何实现它。递归应在达到 1000 次调用时停止。
digits :: Integer -> [Integer]
digits x
| x < 1 = []
| x == 1 = [1]
| otherwise = x `mod` 10 : digits (x `div` 10)
squareSum :: [Integer] -> Integer
squareSum (x:xs) = sum (map (^2) (x:xs))
happy :: Integer -> Bool
happy x
| x == 1 = True
| otherwise = (happy . squareSum . digits) x
happyNumbers :: [Integer]
happyNumbers = filter happy [1..500]
digits 函数获取一个整数,并创建一个包含其数字的列表。
squareSum 函数对这些数字求平方,并对它们进行汇总。
happy 是它一遍又一遍地调用自己的函数,但是当它达到 1000 次调用时我需要停止它。
【问题讨论】:
-
我不明白这个问题,也许你可以更好地解释“当它达到 1000 个调用时停止”的意思。另外我认为这个例子可以更简化。