[swift-evolution] [Review] SE-0187: Introduce Sequence.filterMap(_:)
alexito4 at gmail.com
Wed Nov 15 14:27:18 CST 2017
"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."
I was gonna write the same, completely agree with that.
I know Swift is not purely functional and that some don't really care
about functional names, but giving names to concepts is always good
for communication and that's the only reason why FP langs use specific
names for specific types and operations. Even if we don't really carea
bout that, and we just want to pick approachable names for newcomers
Swift already picked "flatMap" (and map, reduce, etc) so the least
think we could to is at least make the name apply to operations that
follow the proper rules.
On Wed, Nov 15, 2017 at 8:16 PM, Stephen Celis via swift-evolution
<swift-evolution at swift.org> wrote:
> On Nov 15, 2017, at 10:39 AM, Tino Heth via swift-evolution
> <swift-evolution at 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
> 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.
> swift-evolution mailing list
> swift-evolution at swift.org
More information about the swift-evolution