Skip to content

Instantly share code, notes, and snippets.

@rnapier
Last active Aug 29, 2015
Embed
What would you like to do?
Curry and flip with ~~ postfixing. I wonder if this is a good idea…
// Based on https://gist.github.com/kristopherjohnson/adde22d2c53adfb756a1
// Warning, this is insanely slow to compile in Beta6 (can take several minutes)
// Remove some of the |> lines to speed things up
// For more on |>, see http://undefinedvalue.com/2014/07/13/fs-pipe-forward-operator-swift
infix operator |> { precedence 50 associativity left }
// "x |> f" is equivalent to "f(x)"
public func |> <T,U>(lhs: T, rhs: T -> U) -> U {
return rhs(lhs)
}
// "Curryinate" operator. Most Swift stdlib higher-order functions are in the form
// f(x: [T], f: (T->Y)) -> Z
// That's really nice for its "f(list) {...}" syntax, but it makes it very hard to compose
// (chain) into more powerful functions. You'd rather they have the form
// f(f: (T->Y))(x: [T])
// Then it would be easy to compose with operators like F#'s |> or Haskell's (.)
// So appending ~~ to the end of a typical Swift function turns it into a composeable function.
postfix operator ~~ { }
postfix public func ~~ <A, B, T>(f: (A, B) -> T) -> (B -> A -> T) {
return { b in { a in f(a, b) } }
}
let numbers = [67, 83, 4, 99, 22, 18, 21, 24, 23, 2, 86]
let seq = SequenceOf(numbers)
func joinedWithCommas(a: [String]) -> String {
return ", ".join(a)
}
let pipeResult =
seq |> filter~~ { $0 % 2 == 0 }
|> sorted~~ { $1 < $0 }
|> map~~ { $0.description }
|> joinedWithCommas
println(pipeResult) // "86, 24, 22, 18, 4, 2"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment