How do I generate memoized recursive functions in Clojure?

前端 未结 8 1016
[愿得一人]
[愿得一人] 2020-12-25 11:31

I\'m trying to write a function that returns a memoized recursive function in Clojure, but I\'m having trouble making the recursive function see its own memoized bindings. I

8条回答
  •  失恋的感觉
    2020-12-25 12:17

    This seems to work:

    (defn make-fibo [y]
      (with-local-vars
          [fib (memoize
                (fn [x]
                  (if (< x 2)
                    y
                    (+ (fib (- x 2)) (fib (dec x))))))]
        (.bindRoot fib @fib)
        @fib))
    

    with-local-vars only provides thread-local bindings for the newly created Vars, which are popped once execution leaves the with-local-vars form; hence the need for .bindRoot.

提交回复
热议问题