aboutsummaryrefslogtreecommitdiff
path: root/stdlib/source/library/lux/control/function/mixin.lux
blob: f70b2f9c38ef4d4b6af110b47e3ccc9c9c08bd4b (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
## Inspired by;
## "The Different Aspects of Monads and Mixins" by Bruno C. d. S. Oliveira

(.module:
  [library
   [lux #*
    [abstract
     [monoid (#+ Monoid)]
     [predicate (#+ Predicate)]
     [monad (#+ Monad do)]]]])

(type: #export (Mixin i o)
  (-> (-> i o) (-> i o) (-> i o)))

(def: #export (mixin f)
  (All [i o] (-> (Mixin i o) (-> i o)))
  (function (mix input)
    ((f mix mix) input)))

(def: #export nothing
  Mixin
  (function (_ delegate recur)
    delegate))

(def: #export (inherit parent child)
  (All [i o] (-> (Mixin i o) (Mixin i o) (Mixin i o)))
  (function (_ delegate recur)
    (parent (child delegate recur) recur)))

(implementation: #export monoid
  (All [i o] (Monoid (Mixin i o)))

  (def: identity ..nothing)
  (def: compose ..inherit))

(def: #export (advice when then)
  (All [i o] (-> (Predicate i) (Mixin i o) (Mixin i o)))
  (function (_ delegate recur input)
    (if (when input)
      ((then delegate recur) input)
      (delegate input))))

(def: #export (before monad action)
  (All [! i o] (-> (Monad !) (-> i (! Any)) (Mixin i (! o))))
  (function (_ delegate recur input)
    (do monad
      [_ (action input)]
      (delegate input))))

(def: #export (after monad action)
  (All [! i o] (-> (Monad !) (-> i o (! Any)) (Mixin i (! o))))
  (function (_ delegate recur input)
    (do monad
      [output (delegate input)
       _ (action input output)]
      (wrap output))))

(type: #export (Recursive i o)
  (-> (-> i o) (-> i o)))

(def: #export (from-recursive recursive)
  (All [i o] (-> (Recursive i o) (Mixin i o)))
  (function (_ delegate recur)
    (recursive recur)))