Clojure Koans 递归是偶数?

发布于 2024-11-04 07:26:31 字数 300 浏览 1 评论 0原文

我正在研究 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

泪冰清 2024-11-11 07:26:32

就像 amalloy 说的,用“不”填空。但是,如果您假设参数只能为 0 或正数,则不需要另一个基本情况:dec 确保您始终以 0 结束,并且奇数返回 false,如下所示:

(is-even? 0) ==> base case (= 0 0) ==> true.
(is-even? 1) ==> (not (is-even? (dec 1))
             ==> (not (is-even? 0))
             ==> (not true)
             ==> false
(is-even? 2) ==> (not (is-even? 1))
             ==> (not false)
             ==> true

等等。

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:

(is-even? 0) ==> base case (= 0 0) ==> true.
(is-even? 1) ==> (not (is-even? (dec 1))
             ==> (not (is-even? 0))
             ==> (not true)
             ==> false
(is-even? 2) ==> (not (is-even? 1))
             ==> (not false)
             ==> true

etcetera.

擦肩而过的背影 2024-11-11 07:26:32

数字 n 是偶数,如果:

  1. n 是 0
  2. n-1 不是偶数

所以实际上, 应该足以填补这个空白。最终你会在 (= 0 0) 周围得到 N 个 not,并且其中大多数都抵消了。

A number n is even if either:

  1. n is 0
  2. n-1 is NOT even

So really, not should be enough to fill in that blank. Eventually you wind up with N nots around (= 0 0), and most of them cancel out.

著墨染雨君画夕 2024-11-11 07:26:32

考虑每次递归递减 2。其余的应该是显而易见的:只有当函数以零结尾时,该数字才是偶数。

编辑:显然我错过了有关填写空白的备忘录。这是我想到的正整数的尾调用优化解决方案:

(defn is-even? [n]
    (if (<= n 1)
        (= n 0)
        (is-even? (- n 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:

(defn is-even? [n]
    (if (<= n 1)
        (= n 0)
        (is-even? (- n 2))))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文