-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdynamic_typeclass.js
More file actions
executable file
·54 lines (50 loc) · 1.14 KB
/
dynamic_typeclass.js
File metadata and controls
executable file
·54 lines (50 loc) · 1.14 KB
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
#!/usr/bin/env node
const Functor = {
class: Symbol('Functor'),
map: (f, a) => a[Functor.class].map(f, a),
}
const Applicative = {
class: Symbol('Applicative'),
pure: (cls, a) => cls[Applicative.class].pure(a),
}
const Show = {
class: Symbol('Show'),
show: a => {
const cls = a[Show.class]
if (cls !== undefined)
return cls.show(a)
return a.toString()
}
}
const List = {
cons: (head, tail) => ({
head,
tail,
[Functor.class]: {
map: (f, a) => List.cons(f(a.head), Functor.map(f, a.tail)),
},
[Show.class]: {
show: a => `${a.head}:${Show.show(a.tail)}`,
},
}),
empty: {
[Functor.class]: {
map: (_f, _a) => List.empty,
},
[Show.class]: {
show: _a => '[]',
},
},
[Applicative.class]: {
pure: a => List.cons(a, List.empty),
},
}
{
const { map } = Functor
const { pure } = Applicative
const { show } = Show
const { cons } = List
const l = cons(1, pure(List, 2))
const m = map(i => i + 1, l)
console.log(show(m))
}