Last active
November 28, 2015 22:12
-
-
Save kristopherjohnson/7a8b530f25245de2775e to your computer and use it in GitHub Desktop.
F#-style pipe-forward chaining operators for Swift that unwrap Optional values
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
// 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"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See https://gist.github.com/kristopherjohnson/ed97acf0bbe0013df8af for the non-Optional F#-style pipe-forward operators