aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/function/cont.lux
blob: f6330cbe43ef40a4e40eab89f62ccf43fb9cb434 (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
(;module:
  lux
  (lux (macro [ast])
       (control functor
                applicative
                monad)
       (data (coll list))
       function))

## [Types]
(type: #export (Cont a)
  {#;doc "Delimited continuations."}
  (All [b]
    (-> (-> a b) b)))

## [Syntax]
(macro: #export (@lazy tokens state)
  {#;doc (doc "Delays the evaluation of an expression, by wrapping it in a continuation 'thunk'."
              (@lazy (some-computation some-input)))}
  (case tokens
    (^ (list value))
    (let [blank (ast;symbol ["" ""])]
      (#;Right [state (list (` (;lambda [(~ blank)] ((~ blank) (~ value)))))]))
    
    _
    (#;Left "Wrong syntax for @lazy")))

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

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

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

## [Structs]
(struct: #export _ (Functor Cont)
  (def: (map f ma)
    (lambda [k] (ma (. k f)))))

(struct: #export _ (Applicative Cont)
  (def: functor Functor<Cont>)

  (def: (wrap a)
    (@lazy a))

  (def: (apply ff fa)
    (@lazy ((run ff) (run fa)))))

(struct: #export _ (Monad Cont)
  (def: applicative Applicative<Cont>)

  (def: join run))