Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

Are arrays monads in modern javascript

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:

  1. left identity (satisfied):
const value = 10
const array = [value]
const twice = (value) => [value, value]
array.flatMap(twice) === twice(value) // both [10, 10]
  1. right identity (satisfied):
const array = [10]
const wrap = (value) => [value]
array.flatMap(wrap) === array // both [10]
  1. 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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...