Last active
          March 15, 2021 14:07 
        
      - 
      
- 
        Save cobalamin/e78813d456b795a86d64 to your computer and use it in GitHub Desktop. 
    >>=, the "monad" bind operator, in Swift
  
        
  
    
      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
    
  
  
    
  | 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