-
Notifications
You must be signed in to change notification settings - Fork 0
/
listSpec.ts
76 lines (62 loc) · 1.53 KB
/
listSpec.ts
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
import {
clone,
concat,
empty,
flatten,
List,
flatMap,
isEmpty,
head,
map,
of,
tail,
toString,
} from './list';
import * as Maybe from './maybe';
import * as assert from 'assert';
function testEqual<T>(a: List<T>, b: List<T>): void {
if (isEmpty(a) && isEmpty(b)) {
console.log('test passed');
return;
}
if (isEmpty(a) || isEmpty(b)) {
assert(false);
return;
}
const x = a.val;
const y = a.val;
assert(x.val === y.val);
return testEqual(x.next, y.next);
}
const x = of(2);
const y = of(3);
const z = concat(y, x);
// clone
testEqual(z, clone(z));
// head
testEqual(Maybe.flatMap(of, head(z)), x);
testEqual(Maybe.flatMap(of, head(empty())), empty());
// tail
testEqual(tail(concat(z, x)), z);
testEqual(tail(x), empty());
// map
testEqual(map(x => x * x, z), concat(of(9), of(4)));
// flatten
testEqual(flatten(of(z)), z);
testEqual(flatten(concat(of(z), of(x))), concat(z, x));
// monadic laws
const byThree = (val: number): List<number> => of(val * 3);
const byFour = (val: number): List<number> => of(val * 4);
const a = 3;
const f = byThree;
// Left identity: unit(a).bind(f) === f(a)
// flatMap(f, of(a)) === f(a);
testEqual(flatMap(f, of(a)), f(a));
const m = of(3);
// Right identity: m.bind(unit) === m;
// flatMap(of, m) === m;
testEqual(flatMap(of, m), m);
const g = byFour;
// Associativity: m.bind(f).bind(g) === m.bind(x => f(x).bind(g))
// flatMap(g, flatMap(f, m)) === flatMap(x => flatMap(g, f(x)), m);
testEqual(flatMap(g, flatMap(f, m)), flatMap(x => flatMap(g, f(x)), m));