-
-
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
有用なイディオムありがとうございます。
((fn
のところにどうも見覚えがあったのですが、distinct
の実装でした。ごく自然に無名関数の再帰ができて便利ですね。今回は「外から呼び出すのは一回」なのに加えてrecurすべき関数が自明だったので、loopになおしてみました。( #file_pe_2_2.clj )
named-let大好きなScheme脳なので、loop構文つかえると見るや、つい使ってしまいます。
リンク先の
r-reduce
、まだあまり読めてないのですが(特にretn
の役割)、例にあるいろんなシーケンス処理関数の基礎に使えるのかっこいいですね。