Closed evilsoft closed 6 years ago
Ok...nm the second part, I see that depth is set to 1
on when calling flatMap
.
EDIT: For my contrived example, would be better with map
anyway...
([ 23, 23]).map(x => [ x, x + 1])
without the nesting.
It’s a prototype method in Array, so it must always only return an array.
It’s a prototype method in Array, so it must always only return an array.
Sorry, I mean the mappingFunction that is passed to flatMap
...
And is that true that all prototype
methods must return an Array
? I mean Array.prototype.length
returns a Number
. But I may not understand what you mean.
length isn’t a method, it’s an own property. But in this case it’s array flatMap, not a monadic flatMap.
Oh right bad example.
What about toString
, includes
or something like indexOf
Sure, it’s not a strict requirement - but since it uses an IsArray check, what else would it return but an array?
So, if I follow FlattenIntoArray
down to 3. -> c. -> iv. -> 1.
it looks like if the element is not an Array it sets shouldFlatten
to false.
I would expect a TypeError
here when using flatMap
. Seems like it will just provide identity.
So as it is written, seems like that is not a constraint on the mappingFunction
.
I would say we would expect (for flatMap
anyway) that it does not allow a function that return a non-Array.
All that said, it would be nice to enforce that...
But it will be harder to reuse FlattenIntoArray
for both cases and does not match the general "feel" of loose-y goose-y javascript
Most of us that use functions like flatMap
in our day to day will probably just continue using our library functions that handle the constraint for us anyway.
Although it would be nice to have something in JS match already established patterns. And who knows, if it was not for the Promise
spec going the way it did, we would not have fantasy-land, so maybe something else awesome would come out of this.
Closing this issue as it looks like I found my answer.
No. the mapping function does not have to return an Array.
Reading through the
FlattenIntoArray
steps it looks like the mapping function does not have to return anArray
...If that is true, should it be a requirement for the mapping Function to return an Array? If that is not true, should be made a little more clear.
The reason I ask is most libs that use
flatMap
,bind
,chain
, etc have the signature ofMonad m => a -> m b
. So would it make sense to make sure we are matching what the functional programming community expects for a function of this nature.Also in that vein, I could not work out what would happen to a function like
x => [ [ x, x + 1 ] ]
when used with this I would expect something like([ 23, 23 ]).flatMap(x => [ [ x, x + 1 ] ])
to return[ [ 23, 24 ], [ 23, 24 ] ]
is that the case?