Clojure Koans 递归是偶数?
我正在研究 Clojure Koans,并且正在研究递归 koans。
我不明白如何使用递归解决 is-even?
问题。该练习将该函数部分定义为:
(defn is-even? [n]
(if (= n 0)
true
(__ (is-even? (dec n)))))
如果我不想使用递归,那么我会将其定义为 (defn is-even? [n] (= (mod n 2) 0))
但是这违背了练习的目的。
I'm working through Clojure Koans and I'm up to the recursion koans.
I don't understand how to solve is-even?
using recursion. The exercise partially defines this function as:
(defn is-even? [n]
(if (= n 0)
true
(__ (is-even? (dec n)))))
If I don't want to use recursion then I would define it as (defn is-even? [n] (= (mod n 2) 0))
but that goes against the point of the exercise.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
就像 amalloy 说的,用“不”填空。但是,如果您假设参数只能为 0 或正数,则不需要另一个基本情况:
dec
确保您始终以 0 结束,并且奇数返回 false,如下所示:等等。
Like amalloy said, fill the blanks with "not". But provided you assume the argument can only be 0 or positive, you don't need another base case:
dec
makes sure you always end up at 0, and odd numbers return false like this:etcetera.
数字
n
是偶数,如果:n
是 0n-1
不是偶数所以实际上,
不
应该足以填补这个空白。最终你会在(= 0 0)
周围得到 N 个not
,并且其中大多数都抵消了。A number
n
is even if either:n
is 0n-1
is NOT evenSo really,
not
should be enough to fill in that blank. Eventually you wind up with Nnot
s around(= 0 0)
, and most of them cancel out.考虑每次递归递减 2。其余的应该是显而易见的:只有当函数以零结尾时,该数字才是偶数。
编辑:显然我错过了有关填写空白的备忘录。这是我想到的正整数的尾调用优化解决方案:
Consider decrementing by 2 for each recursion. The rest should be obvious: The number is even only if the function ends up with zero.
EDIT: Apparently I missed the memo about filling in the blank. Here is the tail call optimizable solution I had in mind for positive integers: