Clojure入門 - Project Eulerを解いてみる 問4
回文的な商の探索。
以下ネタバレ
ライブラリの一つであるmath.combinatorics
を使ってみる。
leiningenでプロジェクトを作成し、project.clj
でdependency指定。その後ロジックを記述するcore.clj
内にuse
でライブラリ使用を宣言する。
あとは単にcartesian-product
を使うだけ。
(use 'clojure.math.combinatorics) (defn palindrome [n] (= (list* (str n)) (reverse (str n)))) (defn largest_palindrome [] (apply max (filter palindrome (map #(apply * %) (apply cartesian-product (repeat 2 (range 100 1000)))))))
ここに至ってようやくapply
を理解する。今までサンプルコードなどを観ていても(reduce + col)
と(apply + col)
ってどう違うんだろう?と疑問に思っていたのが氷解。
(reduce + [a b c d])
は(+ (+ (+ a b) c) d)
なのに対して(apply + [a b c d])
は(+ a b c d)
になる。Pythonでいうところのargument unpackingだ。