I am kinda new to functional programming and I now want to figure out if arrays in modern javascript are monads. Arrays in modern javascript now have the flatMap method (this method was added recently https://tc39.es/ecma262/#sec-array.prototype.flatmap). I was able to satisfy all of the monad laws using this method. Now I want to figure out if I'm actually correct but I have not been able to find a resource that validates this claim. I have found a statement that arrays are almost monads, but not quite, but this statement was made before flatMap was added. (https://stackoverflow.com/a/50478169/11083823)
These are the validations of the monad laws:
const value = 10
const array = [value]
const twice = (value) => [value, value]
array.flatMap(twice) === twice(value) // both [10, 10]
const array = [10]
const wrap = (value) => [value]
array.flatMap(wrap) === array // both [10]
const array = [10]
const twice = (value) => [value, value]
const doubled = (value) => [value * 2]
array.flatMap(twice).flatMap(doubled) === array.flatMap(doubled).flatMap(twice) // both [20, 20]
Yes, arrays are monads.
In Haskell, we can use use a monadic bind on lists like so:
λ> [1, 2, 3] >>= \a -> [a, 0 - a]
[1,-1,2,-2,3,-3]
Here's the haskell Monad instance for a list: https://hackage.haskell.org/package/base-4.14.1.0/docs/src/GHC.Base.html#line-1133
Here's a resource that explains the list monad: https://en.wikibooks.org/wiki/Haskell/Understanding_monads/List
PS. Monads are a mathematical formalism, and are language agnostic.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With