Last active
April 26, 2018 09:05
-
-
Save AbelToy/7a0b063d316cfad73511aedff5190e36 to your computer and use it in GitHub Desktop.
Function composition in swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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