-
-
Save plaster/d34487ab2ba5a3f375f3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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 | |
)) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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) | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
その再帰もありましたか > @plaster @kohyama
このパターンも想定していませんでした.今回,本当にいろいろと勉強になります.「末尾再帰 = ループ」と考えれば
loop
-recur
でも書けますね: