Skip to content

Commit c58446c

Browse files
committed
Add lesson 7 examples
1 parent 0e5d5a8 commit c58446c

File tree

2 files changed

+61
-8
lines changed

2 files changed

+61
-8
lines changed

examples/6-semigroups-types.js

Lines changed: 25 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ const {Map} = require('immutable-ext')
66

77
// Sum container adds semigroup structure
88
// via the 'concat' method
9-
const Sum = x =>
10-
({
9+
const Sum = x => ({
10+
1111
// make x accessible via 'x' prop
1212
x,
1313

@@ -27,8 +27,7 @@ console.log(
2727

2828

2929
// All container add logical (boolean) 'concat'
30-
const All = x =>
31-
({
30+
const All = x => ({
3231
x,
3332
concat: ({x: y}) => All(x && y),
3433

@@ -43,8 +42,7 @@ console.log(
4342

4443

4544

46-
const First = x =>
47-
({
45+
const First = x => ({
4846
x,
4947

5048
// throw away the arg and keep our First
@@ -69,7 +67,28 @@ const acct2 = Map({
6967
friends: ['Gatsby']
7068
})
7169

70+
71+
// The semigroup structure combines both objects componentwise
7272
// individual custom 'concat' applies in each component
7373
const res = acct1.concat(acct2)
7474

7575
console.log(res.toJS())
76+
77+
78+
79+
// from the comments to video
80+
// x must be an Either
81+
const FirstEither = x => ({
82+
fold: f => x.fold(f, f),
83+
concat: o => x.isLeft ? o : First(x)
84+
})
85+
86+
87+
const find = (xs, f) => List(xs)
88+
.foldMap(
89+
x => FirstEither(f(x) ? Right(x) : Left()),
90+
First.empty
91+
)
92+
.fold(x => x)
93+
94+

examples/types-semigroups.js renamed to examples/7-semigroups-examples.js

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
const { Map } = require('immutable-ext')
2+
13
const result = [1,3].concat([4,5]).concat([5,6,7])
24

35
console.log(result)
@@ -63,8 +65,6 @@ console.log(resFalse)
6365
console.log(resTrue)
6466

6567

66-
67-
6868
const First = x =>
6969
({
7070
x,
@@ -79,3 +79,37 @@ const First = x =>
7979
const resFirst = First("bla").concat(First("last"))
8080

8181
console.log(resFirst)
82+
83+
84+
// Wrap each prop into corresponding Semigroup!
85+
86+
// User account 1
87+
const acc1 = Map({
88+
89+
// First takes first when combined
90+
name: First('Nico'),
91+
92+
// All applies logical all
93+
isPaid: All(true),
94+
95+
// Sum sums the numbers when combined
96+
points: Sum(10),
97+
98+
// Array already has 'concat' method
99+
friends: ['Franklin']
100+
})
101+
102+
const acc2 = Map({
103+
name: First('Nico'),
104+
isPaid: All(false),
105+
points: Sum(2),
106+
friends: ['Gatsby']
107+
})
108+
109+
const res = acc1.concat(acc2)
110+
111+
console.log(
112+
'Combine: ', acc1.toJS(),
113+
'\n with: ', acc2.toJS(),
114+
'\n yields: ', res.toJS()
115+
)

0 commit comments

Comments
 (0)