> On Nov 15, 2017, at 10:39 AM, Tino Heth via swift-evolution 
> <swift-evolution@swift.org> wrote:
> 
> So conceptionally, both overrides are equivalent: The transformation always 
> produces something — an Optional, and that can contain a value, or it can be 
> empty, just like an array.
> You also see that the flatten step really does what it says: It removes one 
> layer of objects, and leaves a flush surface without gaps.
> 
> So, that should really be my last word in this discussion — I won’t add an 
> animation or start singing about Optionals ;-)


Your logic makes sense but doesn’t account for where “flatMap” came from and 
the expectations of how “flatMap” should work.

In functional programming, “map” must preserve structure (the container shape 
should stay the same), and “flatMap” must use the same structure throughout, 
including the return value of the higher order function it takes.

map :: (a -> b) -> m a -> m b
flatMap :: (a -> m b) -> m a -> m b

You may argue that Swift isn’t really a functional language and doesn’t have to 
adhere to functional rules, but as long as it adopts functional nomenclature, 
it should do its best to behave with functional expectations. It’s actually 
impossible to write “flatMap” as written above against a protocol like Sequence 
because Swift lacks higher kinded types, but we can at least approximate the 
behavior that functional programmers expect by narrowing the scope of what’s 
appropriate to return from that higher order function, which is in this case a 
sequence (of which Optional is not).

In fact, I’d rather make “flatMap” stricter by requiring that higher order 
function to return an Array! This of course would kill some ergonomics, but 
it’d at least make things easier to reason about when you always get an Array 
out the other side.

Stephen
https://www.pointfree.co
_______________________________________________
swift-evolution mailing list
swift-evolution@swift.org
https://lists.swift.org/mailman/listinfo/swift-evolution

Reply via email to