Created
May 4, 2015 18:21
-
-
Save hirad/bbf7812ea4a9e27e4156 to your computer and use it in GitHub Desktop.
Simple List Comprehensions in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
infix operator <- { associativity right precedence 140 } | |
infix operator |? { associativity right precedence 140 } | |
func |? <S>(source: [S], predicates: [(s: S) -> Bool]) -> [S] { | |
var ps = predicates | |
return count(ps) > 0 ? (filter(source, ps.removeLast())) |? ps : source | |
} | |
func <-<S, T>(transform: (s: S) -> T, source: [S]) -> [T] { | |
return map(source, transform) | |
} | |
// In Haskell, this would be [ x * 2 | x <- [1..20], x `mod` 2 == , x `mod` 3 == 0 ] | |
let output = { $0 * 2 } <- [Int](1...20) |? [{ $0 % 2 == 0 }, { $0 % 3 == 0 }] | |
println(output) // => [12, 24, 36] | |
// TODO: In Haskell, you can also draw from multiple lists: | |
// [ x*y | x <- [1..20], y <- [5..25]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment