Skip to content

Instantly share code, notes, and snippets.

@nikolaykasyanov
Last active February 3, 2018 23:27
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nikolaykasyanov/bf3e26852b73e564778d to your computer and use it in GitHub Desktop.
Save nikolaykasyanov/bf3e26852b73e564778d to your computer and use it in GitHub Desktop.
Swift & Monads
// 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))
}
}
@tel
Copy link

tel commented Aug 17, 2014

It's technically Haskell style to define flatMap/(>>=) directly as well.

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