MostlyAdequate / mostly-adequate-guide

Mostly adequate guide to FP (in javascript)
Other
23.43k stars 1.87k forks source link

The static method List.of doesn't flatten arrays #513

Closed lp74 closed 5 years ago

lp74 commented 5 years ago

The List.of method doesn't flatten arrays. Passing [a] as arguments, it wraps the array as [[a]].

const list = List.of([1,2]); // list.$value === [[1,2]];

Is there a reason?

KtorZ commented 5 years ago

Yes! Why would it flatten it :sweat_smile: ? of is use to put a value in context of a given Functor. If you want to put a Functor inside a Functor, that's totally fine.

of :: Functor f => a -> f a

Remember that in a Hindley-Milner type signature, lowercase letters are variables that can represent any type (modulo the constraints we put upfront). Same letters corresponds to same types. So, if you give of a list of [a], you end up with:

of :: Functor f => [a] -> f [a]

Now, we can also specialize the Functor because, we know it's a list, and our specialized signature become:

of :: [a] -> [[a]] 

So, no problem :)

lp74 commented 5 years ago

Thank you for the explanation