From cdd46053a96d4215fb12ffa82114249da6b11e66 Mon Sep 17 00:00:00 2001 From: Kenneth Kostresevic Date: Thu, 16 Dec 2021 15:56:29 +0100 Subject: [PATCH 1/3] Solve recursion --- src/koans/14_recursion.clj | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/src/koans/14_recursion.clj b/src/koans/14_recursion.clj index ca29784..d108809 100644 --- a/src/koans/14_recursion.clj +++ b/src/koans/14_recursion.clj @@ -3,21 +3,27 @@ (defn is-even? [n] (if (= n 0) - __ - (___ (is-even? (dec n))))) + true + (not (is-even? (dec n))))) (defn is-even-bigint? [n] (loop [n n acc true] (if (= n 0) - __ + acc (recur (dec n) (not acc))))) (defn recursive-reverse [coll] - __) + (loop [coll coll acc '()] + (if (= coll []) + acc + (recur (rest coll) (conj acc (first coll)))))) (defn factorial [n] - __) + (loop [n n acc n] + (if (= n 1) + acc + (recur (dec n) (* acc (dec n)))))) (meditations "Recursion ends with a base case" From 4bd3bc9a72efcb8a219fb43f4e3349cd46e838a1 Mon Sep 17 00:00:00 2001 From: Kenneth Kostresevic Date: Fri, 17 Dec 2021 13:02:05 +0100 Subject: [PATCH 2/3] Improve recursive-reverse --- src/koans/14_recursion.clj | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/koans/14_recursion.clj b/src/koans/14_recursion.clj index d108809..5e05015 100644 --- a/src/koans/14_recursion.clj +++ b/src/koans/14_recursion.clj @@ -14,10 +14,10 @@ (recur (dec n) (not acc))))) (defn recursive-reverse [coll] - (loop [coll coll acc '()] - (if (= coll []) - acc - (recur (rest coll) (conj acc (first coll)))))) + (loop [[head & tail] coll new-coll '()] + (if-not head + new-coll + (recur tail (conj new-coll head))))) (defn factorial [n] (loop [n n acc n] From 807e32abbb2599c3848eb719e87db47fcfe9efc4 Mon Sep 17 00:00:00 2001 From: Kenneth Kostresevic Date: Fri, 17 Dec 2021 13:03:37 +0100 Subject: [PATCH 3/3] Avoid extra decrementation in factorial --- src/koans/14_recursion.clj | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/koans/14_recursion.clj b/src/koans/14_recursion.clj index 5e05015..81abc0c 100644 --- a/src/koans/14_recursion.clj +++ b/src/koans/14_recursion.clj @@ -20,10 +20,10 @@ (recur tail (conj new-coll head))))) (defn factorial [n] - (loop [n n acc n] + (loop [n n acc 1] (if (= n 1) acc - (recur (dec n) (* acc (dec n)))))) + (recur (dec n) (* acc n))))) (meditations "Recursion ends with a base case"