@@ -539,7 +539,7 @@ randIter.next() // Each execution gives a random value, expression is evaluated
539
539
540
540
## Monoid
541
541
542
- An object with a function that "combines" that object with another of the same type.
542
+ An object with a function that "combines" that object with another of the same type (semigroup) which has an "identity" value .
543
543
544
544
One simple monoid is the addition of numbers:
545
545
@@ -548,11 +548,13 @@ One simple monoid is the addition of numbers:
548
548
```
549
549
In this case number is the object and ` + ` is the function.
550
550
551
- An "identity" value must also exist that when combined with a value doesn't change it .
551
+ When any value is combined with the "identity" value the result must be the original value. The identity must also be commutative .
552
552
553
553
The identity value for addition is ` 0 ` .
554
554
``` js
555
555
1 + 0 // 1
556
+ 0 + 1 // 1
557
+ 1 + 0 === 0 + 1
556
558
```
557
559
558
560
It's also required that the grouping of operations will not affect the result (associativity):
@@ -573,15 +575,10 @@ The identity value is empty array `[]`
573
575
;[1 , 2 ].concat ([]) // [1, 2]
574
576
```
575
577
576
- If identity and compose functions are provided, functions themselves form a monoid:
578
+ As a counterexample, subtraction does not form a monoid because there is no commutative identity value :
577
579
578
580
``` js
579
- const identity = (a ) => a
580
- const compose = (f , g ) => (x ) => f (g (x))
581
- ```
582
- ` foo ` is any function that takes one argument.
583
- ```
584
- compose(foo, identity) ≍ compose(identity, foo) ≍ foo
581
+ 0 - 4 === 4 - 0 // false
585
582
```
586
583
587
584
## Monad
0 commit comments