Skip to content

Instantly share code, notes, and snippets.

@rylev
Created June 3, 2014 23:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rylev/895da063f79d8b81baa9 to your computer and use it in GitHub Desktop.
Save rylev/895da063f79d8b81baa9 to your computer and use it in GitHub Desktop.
enum Maybe<T> {
case Just(T)
case None
func maybe(def: T, fn: (T) -> (T)) -> T {
switch self {
case let Just(x): return fn(x)
case None: return def
}
}
func fromMaybe(def: T) -> T {
switch self {
case let Just(x): return x
case None: return def
}
}
}
let just : Maybe<Int> = .Just(1)
let none : Maybe<Int> = .None
just.maybe(10) { val in val + 100 } // 101
none.maybe(10) { val in val + 2 } // 10
func listToMaybe<T>(list: Array<T>) -> Maybe<T> {
if list.count != 0 {
return .Just(list[0])
} else {
return .None
}
}
listToMaybe([1,2,3]) // Just 1
listToMaybe([]) // None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment