当记忆时,部分与函数文字 [英] Partial vs function literal when memoize
问题描述
这让我有点脑筋:
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)
我想知道这是因为函数字面量(第一个版本)每次被调用/评估,因此 memoize
是每次重新创建(重新记忆),因此没有真正有任何真正有意义的记忆,而第二个与 partial
实际上返回一个固定的函数只评估一次,其中 memoize
的相同值因此每次使用(类似封闭,虽然我不认为这被认为是一个真正的闭包)
I would like to know if the reason for this is because the function literal (first version) is called/evaluated every time, thus the memoize
is "recreated" (re-memorized) each time, therefore not really having any true meaningful "memorization" at all, while the second one with partial
is actually returning a fixed function that is evaluated just once, where the same value of memoize
is thus used every time (sort of like a closure though I don't think this qualifies as a true "closure")
我是否正确?
推荐答案
code> memoize 不以任何方式修改其参数,因此
Yes, memoize
doesn't modify its argument in any way, so
#((memoize rand-int) 10)
在每次调用时重新创建memoized函数。
recreates the memoized function on each call.
(fn [] ((memoize rand-int) 10))
是等效的。
要从另一个函数调用已记忆函数,需要将其放在Var或closed -over local:
To call a memoized function from another function, you need to put it in a Var or a closed-over local:
(repeatedly 10 (let [r (memoize rand-int)] #(r 10)))
;= (2 2 2 2 2 2 2 2 2 2)
例如,(memoize rand-int)
返回的函数作为参数传递给函数 partial
,然后返回一个闭包,结束(memoize rand-int)
的返回。所以,这非常接近上面的例子(除了由 partial
使用 apply
返回的闭包调用memoized函数)。
In the partial
example, the function returned by (memoize rand-int)
is passed as an argument to the function partial
, which then returns a closure which closes over the return of (memoize rand-int)
. So, this is very close to the example above (except the closure returned by partial
uses apply
to call the memoized function).
这篇关于当记忆时,部分与函数文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!