aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/control/thread.lux
blob: 7d46f3707bf5b34b65338e5a152c3314ef15a6d4 (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
(.module:
  lux
  (lux (control [functor #+ Functor]
                [apply #+ Apply]
                [monad #+ Monad do])
       [io #+ IO]))

(type: #export (Thread ! a)
  (-> ! a))

(type: #export (Box t v)
  {#.doc "A mutable box holding a value."}
  (#.Primitive "#Box" (~ (list t v))))

(def: #export (box init)
  (All [a] (-> a (All [!] (Thread ! (Box ! a)))))
  (function (_ !)
    ("lux box new" init)))

(def: #export (read box)
  (All [! a] (-> (Box ! a) (Thread ! a)))
  (function (_ !)
    ("lux box read" box)))

(def: #export (write value box)
  (All [a] (-> a (All [!] (-> (Box ! a) (Thread ! Any)))))
  (function (_ !)
    ("lux box write" value box)))

(def: #export (run thread)
  (All [a]
    (-> (All [!] (Thread ! a))
        a))
  (thread []))

(struct: #export Functor<Thread>
  (All [!] (Functor (Thread !)))

  (def: (map f)
    (function (_ fa)
      (function (_ !)
        (f (fa !))))))

(struct: #export Apply<Thread>
  (All [!] (Apply (Thread !)))

  (def: functor Functor<Thread>)

  (def: (apply ff fa)
    (function (_ !)
      ((ff !) (fa !)))))

(struct: #export Monad<Thread>
  (All [!] (Monad (Thread !)))

  (def: functor Functor<Thread>)

  (def: (wrap value)
    (function (_ !)
      value))

  (def: (join ffa)
    (function (_ !)
      ((ffa !) !))))

(def: #export (update f box)
  (All [a] (-> (-> a a) (All [!] (-> (Box ! a) (Thread ! a)))))
  (do Monad<Thread>
    [old (read box)
     _ (write (f old) box)]
    (wrap old)))

(def: #export (io thread)
  (All [a]
    (-> (All [!] (Thread ! a))
        (IO a)))
  (function (_ void)
    (thread void)))