【问题标题】:How can I stop a function after a certain number of recursive calls? [duplicate]如何在一定数量的递归调用后停止函数? [复制]
【发布时间】: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 个调用时停止”的意思。另外我认为这个例子可以更简化。

标签: haskell recursion


【解决方案1】:

据我了解,快乐的数字是由happy 生成的序列收敛到 1 的数字,因此您可以返回 True,但 不快乐的 数字是序列永远持续的数字。你想返回False,但现在你的代码只是循环在不开心的数字上。 (例如,happy 1 返回True,但happy 2 挂起。)

这样做的通常方法是引入一个新参数作为倒计时。给您的提示是引入一个辅助函数happy',这样您就不必更改happy 的类型签名。尝试定义:

happy :: Integer -> Bool
happy x = happy' 1000 x

happy' :: Integer -> Integer -> Bool
happy' countDown x
   | x == 1 = True
   | otherwise = (happy' (countDown - 1) . squareSum . digits) x

到目前为止,这个“解决方案”仍然会永远运行,但现在你有了一个countDown 参数!您应该能够添加一个新的受保护的案例来检查 countDown 是否已过期以返回 False

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-16
    • 1970-01-01
    • 2020-03-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-27
    • 2021-09-26
    相关资源
    最近更新 更多