Skip to content

Instantly share code, notes, and snippets.

@ulazdins-afs
Created October 25, 2022 07:28
Show Gist options
  • Select an option

  • Save ulazdins-afs/b7ed3574c7ba4b3bc88ceb2a48d2e819 to your computer and use it in GitHub Desktop.

Select an option

Save ulazdins-afs/b7ed3574c7ba4b3bc88ceb2a48d2e819 to your computer and use it in GitHub Desktop.
import Foundation
///
/// Pipe operator
///
precedencegroup ForwardApplication {
associativity: left
higherThan: AssignmentPrecedence
}
infix operator |> : ForwardApplication
infix operator ?|> : ForwardApplication
public func |> <T, U>(x: T, f: (T) -> U) -> U {
return f(x)
}
public func ?|> <T, U>(x: T?, f: (T) -> U) -> U? {
guard let x = x else { return nil }
return f(x)
}
public func |> <T, U>(x: T, keyPath: KeyPath<T, U>) -> U {
return x[keyPath: keyPath]
}
///
/// Trivial examples
///
func addOne(a: Int) -> Int {
a + 1
}
func timesTwo(a: Int) -> Int {
a * 2
}
let number = 5 |> addOne(a:) |> timesTwo(a:)
let capitalized = "hello" |> URL.init(string:)
///
/// Curry and inspect
///
func reverseCurry<A, B, C>(_ f: @escaping (A, B) -> C) -> (B) -> (A) -> C {
{ (b: B) in
{ (a: A) in
return f(a, b)
}
}
}
func inspect<T>(x: T) -> T {
print(x)
return x
}
///
/// More interesting example
///
let initString = reverseCurry(String.init(data:encoding:))
Data([72, 101,108, 108, 111])
|> initString(.utf8)
|> inspect
?|> \.count
?|> inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment