[swift-evolution] Nested for-in loops syntax

T.J. Usiyan griotspeak at gmail.com
Sun Jul 17 15:10:06 CDT 2016


re: cross (nod to Dave Abrahams for the clean implementation)

/// 'Cartesian product' of two sequences
public func cartesianProduct<Left: Sequence, Right: Sequence>(lhs:Left,
rhs:Right) -> [(Left.Iterator.Element, Right.Iterator.Element)] {
    return lhs.flatMap { x in  rhs.map { (x, $0) } }

}
On Sun, Jul 17, 2016 at 11:54 AM, Nevin Brackett-Rozinsky via
swift-evolution <swift-evolution at swift.org> wrote:

> I think this use-case is too narrow for dedicated syntax in the standard
> library.
>
> However, it should be simple enough for you to write your own function,
> let’s call it `unpack`, which produces a sequence that does what you want.
>
> While you’re at it you could also try writing a `cross` function that
> takes two collections and produces all tuples of their elements, perhaps
> using something like .lazy.map.zip internally, if you need that
> functionality.
>
> One great aspect of Swift is that it makes implementing things like this
> yourself readily achievable. Plus, once we get constrained extensions
> (extension Collection where Element: Collection) you should be able to do
> it that way too.
>
> Alternatively, you might consider whether your data structure itself is
> ideal or if you’d be better off flattening everything into, say, a single
> dictionary that takes a compound key.
>
> Nevin
>
>
>
> On Sun, Jul 17, 2016 at 6:05 AM, Maxim Bogdanov via swift-evolution <
> swift-evolution at swift.org> wrote:
>
>> Hello, community.
>>
>> As I understood from documentation the only way to iterate
>> multidimensional array or a dictionary (with for loop) is this:
>>
>> let multidimensionalDictionary = ["a":["b": "c"], "b":["c": "d"], "c":
>> ["d": "e"]]
>> for (key, value) in multidimensionalDictionary {
>>     for (nestedKey, nestedValue) in value {
>>         print("\(key) -> \(nestedKey) -> \(nestedValue)")
>>     }
>> }
>>
>> What do you think about this syntax?
>> for (key, nestedKey, nestedValue) in multidimensionalDictionary {
>>     print("\(key) -> \(nestedKey) -> \(nestedValue)")
>> }
>>
>>
>> --
>> I'm new to mailing list feature. If I do something wrong please let me
>> know about it.
>>
>> Best regards,
>> Maxim
>>
>> _______________________________________________
>> swift-evolution mailing list
>> swift-evolution at swift.org
>> https://lists.swift.org/mailman/listinfo/swift-evolution
>>
>>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160717/b7868af6/attachment.html>


More information about the swift-evolution mailing list