Note that there are some explanatory texts on larger screens.

plurals
  1. POProject Euler #14 and memoization in Clojure
    primarykey
    data
    text
    <p>As a neophyte clojurian, it was <a href="https://stackoverflow.com/questions/2933051/clojure-for-a-lisp-illiterate">recommended to me</a> that I go through the <a href="http://projecteuler.net/" rel="nofollow noreferrer">Project Euler</a> problems as a way to learn the language. Its definitely a great way to improve your skills and gain confidence. I just finished up my answer to <a href="http://projecteuler.net/index.php?section=problems&amp;id=14" rel="nofollow noreferrer">problem #14</a>. It works fine, but to get it running efficiently I had to implement some memoization. I couldn't use the prepackaged <code>memoize</code> function because of the way my code was structured, and I think it was a good experience to roll my own anyways. My question is if there is a good way to encapsulate my cache within the function itself, or if I have to define an external cache like I have done. Also, any tips to make my code more idiomatic would be appreciated.</p> <pre><code>(use 'clojure.test) (def mem (atom {})) (with-test (defn chain-length ([x] (chain-length x x 0)) ([start-val x c] (if-let [e (last(find @mem x))] (let [ret (+ c e)] (swap! mem assoc start-val ret) ret) (if (&lt;= x 1) (let [ret (+ c 1)] (swap! mem assoc start-val ret) ret) (if (even? x) (recur start-val (/ x 2) (+ c 1)) (recur start-val (+ 1 (* x 3)) (+ c 1))))))) (is (= 10 (chain-length 13)))) (with-test (defn longest-chain ([] (longest-chain 2 0 0)) ([c max start-num] (if (&gt;= c 1000000) start-num (let [l (chain-length c)] (if (&gt; l max) (recur (+ 1 c) l c) (recur (+ 1 c) max start-num)))))) (is (= 837799 (longest-chain)))) </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload