(draft) Functional JS

by ilyavf

This is a post in progress.

# Some terminology and definitions

## Monoid and Semigroup

### Examples first:
– The integers under addition is a monoid.
– The positive numbers under addition is a semigroup (no identity element).

### Definitions:

Monoid is a system (a type plus an operation) that obeys the following three rules [1]:
– Rule 1 (Closure): The result of combining two things is always another one of the things: 1 + 2 = 3
– Rule 2 (Associativity): When combining more than two things, which pairwise combination you do first doesn’t matter: 1 + (2 + 3) = (1 + 2) + 3
– Rule 3 (Identity element): There is a special thing called “zero” such that when you combine any thing with “zero” you get the original thing back: 1 + 0 = 1

Semigroup is a system that obeys the first two rules but lacks an identity element.

#Maybe monad

var log = function (x) { console.log(x); };
_.map(log, [1,2,3])
>>> 1
>>> 2
>>> 3
>>> [1, 2, 3]

_.map(log, null)
>>> TypeError: Cannot read property 'length' of null

_.maybe(_.map)(log, [1,2,3])
>>> 1
>>> 2
>>> 3
>>> [1, 2, 3]

_.maybe(_.map)(log, null)
>>> undefined

In the example above I used version 0.2 of ramda.js. In other libraries maybe monad wraps a value so that you can compose it with other functions. But in ramda  it wraps a function that you want to behave correctly if there is a null argument instead of expected.

UPDATE: This was true for version 0.2 of ramda but then the “maybe” method was removed and is no longer a part of the library.

# Links
http://fsharpforfunandprofit.com/posts/monoids-without-tears/
http://buzzdecafe.github.io/code/2014/05/16/introducing-ramda/
http://osteele.com/sources/javascript/functional/

Advertisements