Skip to content

Instantly share code, notes, and snippets.

@cobalamin
Last active March 15, 2021 14:07
Show Gist options
  • Save cobalamin/e78813d456b795a86d64 to your computer and use it in GitHub Desktop.
Save cobalamin/e78813d456b795a86d64 to your computer and use it in GitHub Desktop.
>>=, the "monad" bind operator, in Swift
infix operator >>= {
associativity left
precedence 160
}
func >>=<S: SequenceType, T>(source: S, transform: S.Generator.Element -> [T]) -> [T] {
return flatMap(source, transform)
}
func >>=<C : CollectionType, T>(source: C, transform: (C.Generator.Element) -> [T]) -> [T] {
return flatMap(source, transform)
}
func >>=<T, U>(x: T?, f: (T) -> U?) -> U? {
return flatMap(x, f)
}
// [1,2,3] >>= { (i: Int) -> [Int] in [i, -i] }
// => [1, -1, 2, -2, 3, -3]
// (6 as Int?) >>= { $0 * 7 } // => Optional(42)
// (nil as Int?) >>= { $0 * 7 } // => nil
// (10 as Int?) >>= { $0 == 10 ? nil : $0 + 1 } // => nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment