Skip to content

Instantly share code, notes, and snippets.

@tjeerdintveen
Created February 17, 2017 11:35
Show Gist options
  • Save tjeerdintveen/57a489424aace96f5790d58d02dad6fd to your computer and use it in GitHub Desktop.
Save tjeerdintveen/57a489424aace96f5790d58d02dad6fd to your computer and use it in GitHub Desktop.
import UIKit
// Naive implementation of a piping operator.
func stringToInt(_ str: String) -> Int {
return Int(str)! //force unwrap for demonstration purposes
}
func intToFloat(_ int: Int) -> Float {
return Float(int)
}
// Original way, but can be cumbersome to read with nesting multiple functions.
intToFloat(stringToInt("10"))
// Introducing combine function to make one function out of two.
func combine<T, U, V>(_ lhs: @escaping ((T) -> U), _ rhs: @escaping ((U) -> V)) -> (T) -> V {
return { t in
return rhs(lhs(t))
}
}
let stringToFloat = combine(stringToInt, intToFloat)
// String to float is now a single function. But still not super readable when combining multiple functions.
stringToFloat("10")
// Combine function but as an infix operator, goal is to increase readability of use (if custom operators are agreed upon with coworkers)
// Elixir-like piping operator <3
infix operator |> : AdditionPrecedence
func |><T, U, V>(_ lhs: @escaping ((T) -> U), _ rhs: @escaping ((U) -> V)) -> (T) -> V {
return { t in
return rhs(lhs(t))
}
}
func doubleFloat(_ float: Float) -> Float {
return float * 2
}
// Now we can pipe functions.
let stringToTwiceDoubledFloat =
stringToInt
|> intToFloat
|> doubleFloat
|> doubleFloat
stringToTwiceDoubledFloat("2000") // 8000
// TODO: optional handling and multiple parameter handling.
// Now we can pipe multiple functions, e.g.
/*
parseData
|> toJSON
|> toModel
|> toCollection
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment