Created
January 18, 2018 16:56
-
-
Save DanielCardonaRojas/c738f8e727b627ba2b276106f7ed2110 to your computer and use it in GitHub Desktop.
Function combinators
This file contains hidden or 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
/* -------------- Higher order function combinators ---------------- */ | |
// Composition operators | |
infix operator >>> | |
func >>> <A,B,C> (aToB: @escaping (A) -> B, bToC: @escaping (B) -> C) -> (A) -> C { | |
return { a in aToB(a) |> bToC } | |
} | |
infix operator <<< | |
func <<< <A,B,C> (bToC: @escaping (B) -> C, aToB: @escaping (A) -> B) -> (A) -> C { | |
return { a in bToC <| aToB(a) } | |
} | |
// Pipe operators | |
infix operator |> | |
func |> <B,C> (value: B, bToC: (B) -> C) -> C { | |
return bToC(value) | |
} | |
infix operator <| | |
func <| <B,C> (bToC: (B) -> C, value: B) -> C { | |
return bToC(value) | |
} | |
// Arrow like operators (&&&) | |
infix operator &&& | |
func &&& <B,C,D> (bToC: @escaping (B) -> C, bToD: @escaping (B) -> D) -> (B) -> (C, D) { | |
return { b in (bToC(b), bToD(b)) } | |
} | |
// MARK: - TEST | |
let incrementar = {x in x + 1} | |
let duplicar = {x in x * 2} | |
let even = {x in x % 2 == 0 } | |
let greaterThan3 = { x in x > 3 } | |
let test1 = incrementar(3) |> duplicar | |
print(test1) | |
let test2 = incrementar >>> duplicar | |
print(test2(5)) | |
let test3 = (even &&& greaterThan3) >>> { (f ,s) in f && s } | |
print(test3(6)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment