Skip to content

Instantly share code, notes, and snippets.

@plumhead
Created June 8, 2014 21:09
Show Gist options
  • Save plumhead/bf359b6fc3833ebd3cd2 to your computer and use it in GitHub Desktop.
Save plumhead/bf359b6fc3833ebd3cd2 to your computer and use it in GitHub Desktop.
Partition and Choose
operator infix |> {associativity left precedence 140}
func |> <T,U> (left: @auto_closure () -> T,right: T -> U) -> U {
return right(left())
}
func partition<T>(f : T -> Bool)(a : Array<T>) -> (left: Array<T>, right: Array<T>) {
var (leftpartition,rightpartition) = (Array<T>(),Array<T>())
for (index, value) in enumerate(a) {
if f(value) {
leftpartition.append(value)
}
else {
rightpartition.append(value)
}
}
return (leftpartition,rightpartition)
}
func choose<S,T>(f : S -> T?)(a : Array<S>) -> Array<T> {
var result = Array<T>()
for (index, value) in enumerate(a) {
if let r = f(value) {
result.append(r)
}
}
return result
}
func greaterThan(n : Int)(v : Int) -> Bool {return n >= v}
let greaterThanThree = greaterThan(3)
let greaterThanFive = greaterThan(5)
let (left,right) = [1,2,3,4,5,6] |> partition (greaterThanThree)
//left will be [1,2,3]
// right will be [4,5,6]
left
right
let (left1,right1) = [1,2,3,4,5,6] |> partition (greaterThanFive)
left1
right1
let nils = [1,2,3,4,5] |> choose {(n : Int) -> Int? in return n > 3 ? n : nil}
nils
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment