Last active
February 3, 2018 23:27
-
-
Save nikolaykasyanov/bf3e26852b73e564778d to your computer and use it in GitHub Desktop.
Swift & Monads
This file contains 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
// Make Optional a monad | |
extension Optional { | |
// Scala style, define `flatMap` directly | |
func flatMap<U>(f: (a: T) -> Optional<U>) -> Optional<U> { | |
switch (self) { | |
case .None: return nil | |
case .Some(let value): return f(a: value) | |
} | |
} | |
// Haskell style, define `join` and use existing `map` implementation (`fmap` in Haskell terms) | |
static func join<U>(s: Optional<Optional<U>>) -> Optional<U> { | |
switch (s) { | |
case .None: return nil; | |
case .Some(let value): return value; | |
} | |
} | |
func bind<U>(f: (a: T) -> Optional<U>) -> Optional<U> { | |
return Optional.join(self.map(f)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It's technically Haskell style to define
flatMap
/(>>=)
directly as well.