簡単な硬貨問題 from IT速報2
ふと気づいたのだが、この問題ってreduceじゃなくてreductionsで書けば、「fの中でvectorを作成してそれを戻り値のvectorに入れて・・・」というvector入れ子状態を避けられる。
(def coins [500 100 50 10 5 1]) (defn f [[last-count remain] coin] ((juxt quot rem) remain coin)) (defn get-coins-reductions [n] (->> coins (reductions f [nil n]) next (map first)))
最終結果として残したい数値と、次の計算に使う数字の両方がある場合はreductionsで返した方が読みやすいし遅延評価も効くしでいいんじゃないか。
あとPythonで言うところのdivmodを(juxt quot rem)で表現できるのに気づいたのも嬉しい。