Search code examples
clojurememoization

Memoize over one parameter


I have a function which takes two inputs which I would like to memoize. The output of the function only depends on the value of the first input, the value of the second input has no functional effect on the outcome (but it may affect how long it takes to finish). Since I don't want the second parameter to affect the memoization I cannot use memoize. Is there an idiomatic way to do this or will I just have to implement the memoization myself?


Solution

  • I'd recommend using a cache (like clojure.core.cache) for this instead of function memoization:

    (defonce result-cache
      (atom (cache/fifo-cache-factory {})))
    
    (defn expensive-fun [n s]
      (println "Sleeping" s)
      (Thread/sleep s)
      (* n n))
    
    (defn cached-fun [n s]
      (cache/lookup
        (swap! result-cache
               #(cache/through
                  (fn [k] (expensive-fun k s))
                  %
                  n))
        n))
    
    (cached-fun 111 500)
    Sleeping 500
    => 12321
    (cached-fun 111 600) ;; returns immediately regardless of 2nd arg
    => 12321
    (cached-fun 123 600)
    Sleeping 600
    => 15129