blob: 924ec4c00502bba968fc39e20648b2fda8e8861e (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
... Inspired by;
... "The Different Aspects of Monads and Mixins" by Bruno C. d. S. Oliveira
(.module:
[library
[lux #*
[abstract
[hash (#+ Hash)]
[monad (#+ do)]]
[control
["." state (#+ State)]]
[data
["." product]
[collection
["." dictionary (#+ Dictionary)]]]]]
["." // #_
["#" mixin (#+ Mixin Recursive)]])
(def: .public memoization
(All [i o]
(Mixin i (State (Dictionary i o) o)))
(function (_ delegate recur)
(function (_ input)
(do {! state.monad}
[memory state.get]
(case (dictionary.get input memory)
(#.Some output)
(in output)
#.None
(do !
[output (delegate input)
_ (state.update (dictionary.put input output))]
(in output)))))))
(type: .public (Memo i o)
(Recursive i (State (Dictionary i o) o)))
(def: .public (open memo)
{#.doc (example "Memoization where the memoized results can be re-used accross invocations.")}
(All [i o]
(:let [Memory (Dictionary i o)]
(-> (Memo i o) (-> [Memory i] [Memory o]))))
(let [memo (//.mixin (//.with ..memoization (//.of_recursive memo)))]
(function (_ [memory input])
(|> input memo (state.result memory)))))
(def: .public (closed hash memo)
{#.doc (example "Memoization confined to a single invocation to the function (not counting any subsequent recursive invocations)."
"Memoized results will be re-used during recursive invocations, but cannot be accessed after the main invocation has ended.")}
(All [i o]
(-> (Hash i) (Memo i o) (-> i o)))
(let [memo (//.mixin (//.with ..memoization (//.of_recursive memo)))
empty (dictionary.empty hash)]
(|>> memo (state.result empty) product.right)))
(def: .public (none hash memo)
{#.doc (example "No memoization at all."
"This is useful as a test control when measuring the effect of using memoization.")}
(All [i o]
(-> (Hash i) (Memo i o) (-> i o)))
(let [memo (//.mixin (//.of_recursive memo))
empty (dictionary.empty hash)]
(|>> memo (state.result empty) product.right)))
|