aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/io.lux
blob: d3e08169e2fc47e49ddf82d0deef6c4ddf8a1e2e (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
(;module: {#;doc "A method for abstracting I/O and effectful computations to make it safe while writing pure functional code."}
  lux
  (lux (control [functor #+ Functor]
                [applicative #+ Applicative]
                [monad #+ do Monad])
       (data ["e" error #+ Error]
             (coll [list]))))

(type: #export (IO a)
  {#;doc "A type that represents synchronous, effectful computations that may interact with the outside world."}
  (-> Void a))

(macro: #export (io tokens state)
  {#;doc (doc "Delays the evaluation of an expression, by wrapping it in an IO 'thunk'."
              "Great for wrapping effectful computations (which will not be performed until the IO is \"run\")."
              (io (exec
                    (log! msg)
                    "Some value...")))}
  (case tokens
    (^ (list value))
    (let [blank (: Code [["" +0 +0] (#;Symbol ["" ""])])]
      (#;Right [state (list (` ("lux function" (~ blank) (~ blank) (~ value))))]))

    _
    (#;Left "Wrong syntax for io")))

(struct: #export _ (Functor IO)
  (def: (map f ma)
    (io (f (ma (:! Void []))))))

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

  (def: (wrap x)
    (io x))

  (def: (apply ff fa)
    (io ((ff (:! Void [])) (fa (:! Void []))))))

(struct: #export _ (Monad IO)
  (def: applicative Applicative<IO>)
  
  (def: (join mma)
    (io ((mma (:! Void [])) (:! Void [])))))

(def: #export (run action)
  {#;doc "A way to execute IO computations and perform their side-effects."}
  (All [a] (-> (IO a) a))
  (action (:! Void [])))

## Process
(type: #export (Process a)
  (IO (Error a)))

(struct: #export _ (Functor Process)
  (def: (map f ma)
    (io (:: e;Functor<Error> map f (run ma)))))

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

  (def: (wrap x)
    (io (:: e;Applicative<Error> wrap x)))

  (def: (apply ff fa)
    (io (:: e;Applicative<Error> apply (run ff) (run fa)))))

(struct: #export _ (Monad Process)
  (def: applicative Applicative<Process>)
  
  (def: (join mma)
    (case (run mma)
      (#e;Success ma)
      ma
      
      (#e;Error error)
      (io (#e;Error error)))))

(def: #export (fail error)
  (All [a] (-> Text (Process a)))
  (io (#e;Error error)))