aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/control/cont.lux
blob: 81f62eccb7f1a04428dd7dbab4d798662ac72c33 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
(;module:
  lux
  (lux (control ["F" functor]
                ["A" applicative]
                monad)
       function
       [macro #+ with-gensyms]
       (macro [code]
              [syntax #+ syntax:])))

(type: #export (Cont i o)
  {#;doc "Continuations."}
  (-> (-> i o) o))

(def: #export (continue k cont)
  {#;doc "Forces a continuation thunk to be evaluated."}
  (All [i o] (-> (-> i o) (Cont i o) o))
  (cont k))

(def: #export (run cont)
  {#;doc "Forces a continuation thunk to be evaluated."}
  (All [a] (-> (Cont a a) a))
  (cont id))

(struct: #export Functor<Cont> (All [o] (F;Functor (All [i] (Cont i o))))
  (def: (map f fv)
    (function [k] (fv (. k f)))))

(struct: #export Applicative<Cont> (All [o] (A;Applicative (All [i] (Cont i o))))
  (def: functor Functor<Cont>)

  (def: (wrap value)
    (function [k] (k value)))

  (def: (apply ff fv)
    (function [k]
      (|> (k (f v))
          (function [v]) fv
          (function [f]) ff))))

(struct: #export Monad<Cont> (All [o] (Monad (All [i] (Cont i o))))
  (def: applicative Applicative<Cont>)

  (def: (join ffa)
    (function [k]
      (ffa (continue k)))))

(def: #export (call/cc f)
  {#;doc "Call with current continuation."}
  (All [a b z]
    (-> (-> (-> a (Cont b z))
            (Cont a z))
        (Cont a z)))
  (function [k]
    (f (function [a] (function [_] (k a)))
       k)))

(syntax: #export (pending expr)
  {#;doc (doc "Turns any expression into a function that is pending a continuation."
              (pending (some-computation some-input)))}
  (with-gensyms [g!k]
    (wrap (list (` (;function [(~ g!k)] ((~ g!k) (~ expr))))))))

(def: #export (portal init)
  (All [i o z]
    (-> i
        (Cont [(-> i (Cont o z))
               i]
              z)))
  (call/cc (function [k]
             (do Monad<Cont>
               [#let [nexus (function nexus [val]
                              (k [nexus val]))]
                _ (k [nexus init])]
               (wrap (undefined))))))

(def: #export (reset scope)
  (All [i o] (-> (Cont i i) (Cont i o)))
  (function [k]
    (k (run scope))))

(def: #export (shift f)
  (All [a]
    (-> (-> (-> a (Cont a a))
            (Cont a a))
        (Cont a a)))
  (function [oc]
    (f (function [a] (function [ic] (ic (oc a))))
       id)))