Skip to content

Instantly share code, notes, and snippets.

@dfrobison
Created March 16, 2022 00:56
Show Gist options
  • Save dfrobison/fda83ca83893400135b054e758991193 to your computer and use it in GitHub Desktop.
Save dfrobison/fda83ca83893400135b054e758991193 to your computer and use it in GitHub Desktop.
Functional programming: pipe forward and forward composition
func incr(_ x: Int) -> Int {
return x + 1
}
func square(_ x: Int) -> Int {
return x * x
}
precedencegroup ForwardApplication {
associativity: left
}
infix operator |>: ForwardApplication
func |> <A, B>(x: A, f: (A) -> B) -> B {
return f(x)
}
2 |> incr |> square
precedencegroup ForwardComposition {
higherThan: ForwardApplication
associativity: left
}
infix operator >>>: ForwardComposition
func >>> <A, B, C>(_ f: @escaping (A) -> B, _ g: @escaping (B) -> C) -> ((A) -> C) {
return { a in g(f(a)) }
}
2 |> incr >>> square
[1, 2, 3]
.map(square)
.map(incr)
[1, 2, 3]
.map(square >>> incr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment