aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/lux/io.lux
blob: 4da9fe8978a0d3559ba7fcfc08d39abb6292f3e5 (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
(.module: {#.doc "A method for abstracting I/O and effectful computations to make it safe while writing pure functional code."}
  [lux #*
   [control
    [functor (#+ Functor)]
    [apply (#+ Apply)]
    [monad (#+ Monad do)]]
   [type
    abstract]
   ["." macro (#+ with-gensyms)
    ["s" syntax (#+ syntax:)]
    ["." template]]])

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

  (def: #export (label thunk)
    (All [a] (-> (-> Nothing a) (IO a)))
    (:abstraction thunk))

  (template: (!io computation)
    (:abstraction (template.with-locals [g!func g!arg]
                    (function (g!func g!arg)
                      computation))))

  (template: (!execute io)
    ## creatio ex nihilo
    ((:representation io) (:coerce .Nothing [])))

  (syntax: #export (io computation)
    {#.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...")))}
    (with-gensyms [g!func g!arg]
      (wrap (list (` ((~! ..label) (function ((~ g!func) (~ g!arg))
                                     (~ computation))))))))

  (def: #export (exit code)
    (-> Int (IO Nothing))
    (!io ("lux io exit" code)))

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

  (structure: #export functor (Functor IO)
    (def: (map f)
      (|>> !execute f !io)))

  (structure: #export apply (Apply IO)
    (def: &functor ..functor)

    (def: (apply ff fa)
      (!io ((!execute ff) (!execute fa)))))

  (structure: #export monad (Monad IO)
    (def: &functor ..functor)

    (def: wrap (|>> !io))
    
    (def: join (|>> !execute !execute !io)))
  )