[swift-evolution] Extending the for loop to have multiple clauses
ilya
ilya.nikokoshev at gmail.com
Wed Dec 9 14:48:37 CST 2015
You can define a 'times' operation to work with any sequences, e.g.
import Foundation
enum Suits: String {
case Spades = "♠"
case Hearts = "♥"
case Diamonds = "♦"
case Clubs = "♣"
}
let suits:[Suits] = [.Spades, .Hearts, .Diamonds, .Clubs]
let ranks = ["A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3",
"2"]
infix operator ⨉ {}
func ⨉<A:SequenceType, B:SequenceType>(lhs: A, rhs: B)
-> [(A.Generator.Element, B.Generator.Element)] {
return lhs
.map{ left in rhs.map{ right in (left, right) }}
.reduce([], combine: +)
}
[1, 2] ⨉ [3, 4]
func shuffled() -> [String] {
var cards:[String] = []
for (suit, rank) in suits ⨉ ranks {
let random = Int(abs(rand())) % (cards.count + 1)
cards.insert(suit.rawValue + rank, atIndex: random)
}
return cards
}
shuffled().joinWithSeparator(" ")
On Wed, Dec 9, 2015 at 23:00 Chris Eidhof via swift-evolution <
swift-evolution at swift.org> wrote:
> I think it could be really nice to extend the for-loop so that it can have
> multiple clauses. Much like in the if-let with multiple clauses, I could
> imagine a for-loop with multiple clauses:
>
> var cards: [(Suit,Rank)] = []
> for x in suits, y in ranks {
> cards.append((x,y))
> }
>
> This would be the same as writing:
>
> var cards: [(Suit,Rank)] = []
> for x in suits {
> for y in ranks {
> cards.append((x,y))}
> }
> }
>
> You could also do something like:
>
> for x in input1, y in (x..<end) {
> // Do something with (x,y)
> }
>
> In fact, once we would have that, we could combine both if-let and for,
> and make it more general, to end up with something like Haskell’s
> do-notation or C#’s LINQ. But that might be taking it too far...
>
> Chris
> _______________________________________________
> 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/20151209/547552f8/attachment.html>
More information about the swift-evolution
mailing list