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だ。