Created
June 3, 2014 23:50
-
-
Save rylev/895da063f79d8b81baa9 to your computer and use it in GitHub Desktop.
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
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