Search code examples
clojure

What is the recommended way to use memoize?


I have occasionally used memoize function. In usually the following form:

(defn- sqrt-denom [iterations]
  (/ 1 (if (= iterations 0)
         2
         (+ 2 (sqrt-denom (dec iterations))))))

(def sqrt-denom (memoize sqrt-denom))

I assumed that it is "proper" to reuse the function name when memoizing. Is this a good practice? Or should I use different names for the non-memoized and memoized functions?


Solution

  • I would never re-use the name of a top-level def, especially when self-referencing. Two choices:

    (defn ^:no-doc sqrt-denom-impl [iterations]
      (/ 1 (if (= iterations 0)
             2
             (+ 2 (sqrt-denom (dec iterations))))))
    
    (def sqrt-denom (memoize sqrt-denom-impl))
    

    or even simpler:

    (def sqrt-denom
      (memoize (fn  [iterations]
        (/ 1 (if (= iterations 0)
               2
               (+ 2 (sqrt-denom (dec iterations))))))