Skip to content

Instantly share code, notes, and snippets.

@praeclarum
Last active August 29, 2015 14:24
Show Gist options
  • Save praeclarum/9bd7451c9326e95fd864 to your computer and use it in GitHub Desktop.
Save praeclarum/9bd7451c9326e95fd864 to your computer and use it in GitHub Desktop.
Some function and SequenceType extensions that I found missing in Swift 2
//
// Seq.swift
//
// Created by Frank A. Krueger on 7/8/15.
// Copyright © 2015 Krueger Systems, Inc. All rights reserved.
// MIT Licensed
//
import Foundation
infix operator |> { associativity left }
/// Pipe a value through a unary function
func |> <X, Y>(x: X, f: X -> Y) -> Y {
return f(x)
}
/// Composition of two unary function
func >> <X, Y, Z>(f: X -> Y, g: Y -> Z) -> X -> Z {
return { g(f($0)) }
}
/// Turns a binary function into a unary function by capturing the first argument
func papply<X, Y, Z>(f: (X, Y) -> Z, _ x: X) -> Y -> Z {
return { f(x, $0) }
}
/// Turns a binary function into a unary function that returns a unary function
func curry<X, Y, Z>(f: (X, Y) -> Z) -> X -> (Y -> Z) {
return { (x: X) in { f(x, $0) } }
}
/// Turns a curried function into a binary function
func uncurry<X, Y, Z>(f: X -> (Y -> Z)) -> (X, Y) -> Z {
return { f($0)($1) }
}
func toDictionary<K, V>(array: [(K, V)]) -> [K: V] {
var r: [K: V] = [:]
for (k, v) in array {
r[k] = v
}
return r
}
extension SequenceType {
func choose<T>(chooser: Self.Generator.Element -> T?) -> [T] {
var r: [T] = []
for x in self {
if let y = chooser(x) { r.append(y) }
}
return r
}
func collect<T>(collector: Self.Generator.Element -> [T]) -> [T] {
var r: [T] = []
for x in self {
r.extend(collector(x))
}
return r
}
func groupBy<TKey>(keySelector: Self.Generator.Element -> TKey) -> [TKey: [Self.Generator.Element]] {
var r: [TKey: [Self.Generator.Element]] = [:]
for x in self {
let k = keySelector(x)
if var a = r[k] {
a.append(x)
r[k] = a
}
else {
r[k] = [x]
}
}
return r
}
func toDictionary<TKey>(keySelector: Self.Generator.Element -> TKey) -> [TKey: Self.Generator.Element] {
var r: [TKey: Self.Generator.Element] = [:]
for x in self {
r[keySelector(x)] = x
}
return r
}
func firstIf(predicate: Self.Generator.Element -> Bool) -> Self.Generator.Element? {
for x in self {
if predicate(x) { return x }
}
return nil
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment