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:
- left identity (satisfied):
const value = 10
const array = [value]
const twice = (value) => [value, value]
array.flatMap(twice) === twice(value) // both [10, 10]
- right identity (satisfied):
const array = [10]
const wrap = (value) => [value]
array.flatMap(wrap) === array // both [10]
- associativity (satisfied):
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]
question from:
https://stackoverflow.com/questions/65905682/are-arrays-monads-in-modern-javascript 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…