Skip to content

Commit de65a07

Browse files
committed
Add coyoneda example
1 parent c10f0a6 commit de65a07

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed

examples/coyoneda.js

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
// Video: https://www.youtube.com/watch?v=WH5BrkzGgQY
2+
3+
const daggy = require('daggy')
4+
const compose = (f, g) => x => f(g(x))
5+
const id = x => x
6+
7+
8+
//===============Define Coyoneda=========
9+
10+
// create constructor with props 'x' and 'f'
11+
// 'x' is our value, 'f' is a function
12+
const Coyoneda = daggy.tagged('x', 'f')
13+
14+
// map composes the function
15+
Coyoneda.prototype.map = function(f) {
16+
return Coyoneda(this.x, compose(f, this.f))
17+
}
18+
19+
Coyoneda.prototype.lower = function() {
20+
return this.x.map(this.f)
21+
}
22+
23+
// lift starts off Coyoneda with the 'id' function
24+
Coyoneda.lift = x => Coyoneda(x, id)
25+
26+
27+
//===============Map over a non-Functor - Set =========
28+
29+
// Set does not have a 'map' method
30+
const set = new Set([1, 1, 2, 3, 3, 4])
31+
32+
console.log("Set is: ", set)
33+
34+
// Wrap set into Coyoneda with 'id' function
35+
const coyo_result = Coyoneda.lift(set)
36+
.map(x => x + 1)
37+
.map(x => `${x}!`)
38+
39+
console.log("Mapped over Set is: ", coyo_result)
40+
41+
// equivalent to buildUpFn = coyo_result.f, our_set = coyo_result.x
42+
const {f: builtUpFn, x: our_set} = coyo_result
43+
44+
console.log("builtUpFn is: ", builtUpFn, "; our_set is: ", our_set)
45+
46+
our_set
47+
.forEach(n => console.log(builtUpFn(n)))
48+
// 2!
49+
// 3!
50+
// 4!
51+
// 5!
52+
53+
54+
//===============Lift a functor in (Array) and achieve Loop fusion=========
55+
Coyoneda.lift([1,2,3])
56+
.map(x => x * 2)
57+
.map(x => x - 1)
58+
.lower()
59+
// [ 1, 3, 5 ]
60+
61+
62+
//===============Make Any Type a Functor=========
63+
// Any object becomes a functor when placed in Coyoneda
64+
65+
const Container = daggy.tagged('x')
66+
67+
const tunacan = Container("tuna")
68+
69+
const res = Coyoneda.lift(tunacan)
70+
.map(x => x.toUpperCase())
71+
.map(x => x + '!')
72+
73+
74+
const {f: fn, x: can} = res
75+
console.log(fn(can.x))
76+
// TUNA!

examples/package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
{
22
"dependencies": {
3+
"daggy": "^0.0.1",
34
"futurize": "^1.0.2"
45
}
56
}

examples/yarn.lock

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22
# yarn lockfile v1
33

44

5+
daggy@^0.0.1:
6+
version "0.0.1"
7+
resolved "https://registry.yarnpkg.com/daggy/-/daggy-0.0.1.tgz#ae9c932c9f7136e655a04afb21e8baadfd0d3707"
8+
59
futurize@^1.0.2:
610
version "1.0.2"
711
resolved "https://registry.yarnpkg.com/futurize/-/futurize-1.0.2.tgz#7cce73efa3eae3a5ce27a3fce69889d478e9ce38"

0 commit comments

Comments
 (0)