blob: 8248b205550c73daa59b5ea850c56aa12f983a4a (
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
|
## 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)
{#.doc (doc "A function which can be mixed with others to inherit their behavior.")}
(-> (-> i o) (-> i o) (-> i o)))
(def: #export (mixin f)
{#.doc (doc "Given a mixin, produces a normal function.")}
(All [i o] (-> (Mixin i o) (-> i o)))
(function (mix input)
((f mix mix) input)))
(def: #export nothing
{#.doc (doc "A mixin that does nothing and just delegates work to the next mixin.")}
Mixin
(function (_ delegate recur)
delegate))
(def: #export (inherit parent child)
{#.doc (doc "Produces a new mixin, where the behavior of the child can make use of the behavior of the parent.")}
(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)
{#.doc (doc "Only apply then mixin when the input meets some criterion.")}
(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)
{#.doc (doc "Executes an action before doing the main work.")}
(All [! i o] (-> (Monad !) (-> i (! Any)) (Mixin i (! o))))
(function (_ delegate recur input)
(do monad
[_ (action input)]
(delegate input))))
(def: #export (after monad action)
{#.doc (doc "Executes an action after doing the main work.")}
(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)
{#.doc (doc "An indirectly recursive function.")}
(-> (-> i o) (-> i o)))
(def: #export (of_recursive recursive)
{#.doc (doc "Transform an indirectly recursive function into a mixin.")}
(All [i o] (-> (Recursive i o) (Mixin i o)))
(function (_ delegate recur)
(recursive recur)))
|