~jojo/Carth

ref: d43904b49f898feb4b2e6ebef26d62e5651047bf Carth/std/memo.carth -rw-r--r-- 506 bytes
d43904b4JoJo std: Add Mutex 1 year, 2 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
;; Memoization
;;
;; A bit like lazy evaluation, but only the result caching part -- no thunk-wise
;; evaluation.

(import std)

(data (Memo a)
  (Memo (Box (Either (Fun Unit a) a))))

(define: (memoize f)
    (forall (a) (Fun (Fun Unit a) (Memo a)))
  (Memo (box (Left f))))

(define: (remember (Memo ptr))
    (forall (a) (Fun (Memo a) a))
  (match (deref ptr)
    (case (Left f) (let ((x (f Unit)))
                     (seq (store (Right x) ptr)
                          x)))
    (case (Right x) x)))