Skip to content

Instantly share code, notes, and snippets.

@plaster

plaster/pe-2.clj Secret

Created December 10, 2012 14:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plaster/d34487ab2ba5a3f375f3 to your computer and use it in GitHub Desktop.
Save plaster/d34487ab2ba5a3f375f3 to your computer and use it in GitHub Desktop.
(defn internal-fold-with-fib-to
[op seed end x0 x1]
(if (< x1 end)
(recur op (op x1 seed)
end
x1
(+ x0 x1))
seed
))
(defn fold-with-fib-to
[op seed end]
(internal-fold-with-fib-to op seed end 0 1)
)
;; 当初 fold-with-fib-to と internal-fold-with-fib-to は
;; 一つの関数で、引数の数でどっちに行くかを分けてみていたのですが
;; recur がうまくいかなかったので、あきらめて2つに分けました
(defn solve []
(fold-with-fib-to
(fn [x sum]
(if (even? x)
(+ x sum)
sum))
0
4000001
))
(defn fold-with-fib-to [op seed end]
(loop [seed seed
x0 0
x1 1]
(if (< x1 end)
(recur (op x1 seed)
x1
(+ x0 x1))
seed
)))
(defn solve [end-inclusive]
(fold-with-fib-to
(fn [x sum]
(if (even? x)
(+ x sum)
sum))
0
(+ 1 end-inclusive)
))
@tnoda
Copy link

tnoda commented Dec 11, 2012

その再帰もありましたか > @plaster @kohyama

このパターンも想定していませんでした.今回,本当にいろいろと勉強になります.「末尾再帰 = ループ」と考えれば loop-recur でも書けますね:

(loop [x 0 y 1 sum 0]
  (if (< x 4000000)
    (recur y (+ x y) (if (even? x) (+ sum x) sum))
    sum))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment