Skip to content

Instantly share code, notes, and snippets.

@zakbarlow1995
Created October 11, 2021 15:04
Show Gist options
  • Save zakbarlow1995/a9fbed102b157312061fe21161cb3f1e to your computer and use it in GitHub Desktop.
Save zakbarlow1995/a9fbed102b157312061fe21161cb3f1e to your computer and use it in GitHub Desktop.
Compose Functions - Returns a function that applies g to the result of f
precedencegroup CompositionPrecedence {
associativity: left
}
infix operator >>>: CompositionPrecedence
func >>><T, U, V>(
f: @escaping (T) -> U,
g: @escaping (U) -> V
) -> (T) -> V {
return { g(f($0)) }
}
@zakbarlow1995
Copy link
Author

Heavily based on the ° operator from Swift 3-era SwiftExperimental.swift file

Example usage:

func randomNumber(max: Int) -> Int {
    let random = Int.random(in 0...max)
    print("Random number: \(random)")
    return random
}

func factors(of number: Int) -> [Int] {
    (1...max).filter { number % $0 == 0 }
}

func toString(numbers: [Int] -> {
    numbers.reduce("Factors: ") { $0 + "\($1) " } 
}

let combined = randomNumber >>> factors >>> toString
print(combined(100))

// Random number: 42
// Factors: 1 2 3 6 7 14 21 42

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment