Skip to content

Instantly share code, notes, and snippets.

@AbelToy
Last active April 26, 2018 09:05
Show Gist options
  • Save AbelToy/7a0b063d316cfad73511aedff5190e36 to your computer and use it in GitHub Desktop.
Save AbelToy/7a0b063d316cfad73511aedff5190e36 to your computer and use it in GitHub Desktop.
Function composition in swift
import Foundation
// identity function
func id<T>(_ x: T) -> T {
return x
}
// compositing functions
infix operator ∘: MultiplicationPrecedence
func ∘<T, U, V> (_ g: @escaping ((U) -> V), _ f: @escaping ((T) -> U)) -> ((T) -> V) {
return { (x: T) -> V in g(f(x)) }
}
func f(_ x: Int) -> Int {
return x + 1
}
func g(_ x: Int) -> Int {
return x * 4
}
func h(_ x: Int) -> Int {
return x * x
}
g(f(2)) // 12
(g ∘ f)(2) // 12
h(g(f(2))) // 144
(h ∘ g ∘ f)(2) // 144
(id ∘ f)(2) // 3
(f ∘ id)(2) // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment