Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Last active November 28, 2015 22:12
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristopherjohnson/7a8b530f25245de2775e to your computer and use it in GitHub Desktop.
Save kristopherjohnson/7a8b530f25245de2775e to your computer and use it in GitHub Desktop.
F#-style pipe-forward chaining operators for Swift that unwrap Optional values
// Pipe-forward operators that unwrap Optional values
operator infix |>! { precedence 50 associativity left }
operator infix |>& { precedence 50 associativity left }
// Unwrap the optional value on the left-hand side and apply the right-hand-side function
public func |>! <T,U>(lhs: T?, rhs: T -> U) -> U {
return rhs(lhs!)
}
// If optional value is nil, return nil; otherwise unwrap it and
// apply the right-hand-side function to it.
//
// (It would be nice if we could name this "|>?", but the ? character
// is not allowed in custom operators.)
public func |>& <T,U>(lhs: T?, rhs: T -> U) -> U? {
if let nonNilValue = lhs {
return rhs(nonNilValue)
}
else {
return nil
}
}
// Examples
let elements = [2, 4, 6, 8, 10]
func reportIndexOfValue(value: Int)(index: Int) -> String {
let message = "Found \(value) at index \(index)"
println(message)
return message
}
// Safe to use |>! if we know we'll find the value
find(elements, 6) |>! reportIndexOfValue(6) // "Found 6 at index 2"
// If left side may be nil, use |>&
find(elements, 3) |>& reportIndexOfValue(3) // nil
find(elements, 4) |>& reportIndexOfValue(4) // {Some "Found 4 at index 1"}
@kristopherjohnson
Copy link
Author

See https://gist.github.com/kristopherjohnson/ed97acf0bbe0013df8af for the non-Optional F#-style pipe-forward operators

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