Partial vs function literally when memoize

This gives me a little brain:

user> (repeatedly 10 #((memoize rand-int) 10)) (7 0 4 8 1 2 2 1 6 9) user> (repeatedly 10 (partial (memoize rand-int) 10)) (8 8 8 8 8 8 8 8 8 8) 

I would like to know the reason is that the literal function (first version) is called / evaluated every time, so memoize “recreated” (re-remembered) every time, therefore it doesn't have any true meaningful “remembering” at all, while the second with partial actually returns a fixed function that is evaluated only once, where the same memoize value is used this way every time (sort of like a closure, although I don’t think it qualifies as a true “closure”)

Am i thinking right?

+5
source share
1 answer

Yes, memoize does not change its argument, so

 #((memoize rand-int) 10) 

recreates the memoized function for each call.

 (fn [] ((memoize rand-int) 10)) 

equivalently.

To call a memoized function from another function, you need to put it in Var or a private local:

 (repeatedly 10 (let [r (memoize rand-int)] #(r 10))) ;= (2 2 2 2 2 2 2 2 2 2) 

In the partial example, the function returned (memoize rand-int) is passed as an argument to the partial function, which then returns a closure that closes on return (memoize rand-int) . So, this is very close to the above example (except for the closure returned by partial , it uses apply to call the memoized function).

+5
source

All Articles