[swift-users] Rational behind having 2 different behaviors for flatMap?
Maxim Veksler
maxim at vekslers.org
Mon Feb 13 18:31:38 CST 2017
Hi everyone,
I've discovered today that Swift will actually choose 2 very differently
behaving types of flatMap implementation based on the input signature.
For a Sequence of options it will call a flatMap that filters out nil's.
For a Sequence of Sequence's it will call a flattening function, without
filtering.
Leading to code that (IMHO) reads very not inconsistency, and unexpected.
Sometime even looking a bit funny such as collection.flatMap.flatMap:
5> let deep = [["1989", nil], [nil, "Red"], [nil, nil]]
deep: [[String?]] = 3 values {
[0] = 2 values {
[0] = "1989"
[1] = nil
}
[1] = 2 values {
[0] = nil
[1] = "Red"
}
[2] = 2 values {
[0] = nil
[1] = nil
}
}
6> deep.flatMap { $0 }
$R1: [String?] = 6 values {
[0] = "1989"
[1] = nil
[2] = nil
[3] = "Red"
[4] = nil
[5] = nil
}
7> deep.flatMap { $0 }.flatMap { $0 }
$R2: [String] = 2 values {
[0] = "1989"
[1] = "Red"
}
I wonder why it was implemented this way?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170214/2a04ffbc/attachment.html>
More information about the swift-users
mailing list