-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheither.js
executable file
·82 lines (67 loc) · 1.96 KB
/
either.js
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
77
78
79
80
81
82
var Type = require('union-type')
var curry = require('ramda').curry
var T = () => true
var I = a => a
var Either = Type({Left: [T], Right: [T]})
var Right = Either.Right
var Left = Either.Left
Either.equals = curry((a, b) => Either.case({
Right: v => b.name === 'Right' && v === Either.extract(b)
, Left: v => b.name === 'Left' && v === Either.extract(b)
}, a))
//:: (a -> b) -> Either a -> Either b
Either.map = curry((f, a) => Either.case({
Right: v => Right(f(v))
, Left: _ => a
}, a))
//:: Either a -> a
Either.extract = Either.case({
Right: I
, Left: I
})
//:: a -> Either _ -> Either a
Either.of = curry((a, b) => Either.case({
Right: _ => Right(a)
, Left: _ => Right(a)
}, b))
//:: (a -> Either b) -> Either a -> Either b
Either.chain = curry((f, a) => Either.case({
Right: v => f(v)
, Left: _ => a
}, a))
//:: (a -> Either b) -> Either a -> Either b
Either.chainLeft = curry((f, a) => Either.case({
Right: _ => a
, Left: v => f(v)
}, a))
//:: (a -> Either b) -> (b -> Either c) -> Either a b -> Either c
Either.bichain = curry((f, g, a) => Either.case({
Right: v => g(v)
, Left: v => f(v)
}, a))
//:: Either a -> Either (a -> b) -> Either b
Either.ap = curry((a, b) => Either.case({
Right: v => b.name === "Right" ? Right(Either.extract(b)(v)) : b
, Left: _ => a
}, a))
//:: (b -> a -> b) -> b -> Either a -> b
Either.reduce = curry((f, b, a) => Either.case({
Right: v => f(b, v)
, Left: _ => b
}, a))
//:: (Either a -> b) -> Either a -> b
Either.extend = curry((f, a) => Either.case({
Right: _ => Right(f(a))
, Left: _ => a
}, a))
//:: (a -> c) -> (b -> c) -> Either a b -> c
Either.cata = curry((f, g, a) => Either.case({
Right: g
, Left: f
}, a))
//:: (a -> b) -> (c -> d) -> Either a c -> Either b d
Either.bimap = curry((f, g, a) => Either.case({
Right: v => Right(g(v))
, Left: v => Left(f(v))
}, a))
module.exports = Either