Created
June 5, 2014 21:20
-
-
Save joshaber/1a3d6af1a81e86fb6322 to your computer and use it in GitHub Desktop.
Functor
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
class F<A> { | |
} | |
protocol Functor { | |
typealias A | |
typealias B | |
typealias FA = F<A> | |
typealias FB = F<B> | |
func fmap(a: FA, fn: (A -> B)) -> FB | |
} | |
class Maybe<A: Any>: F<A> { | |
var value: A? | |
init(_ v: A) { | |
value = v | |
} | |
init() {} | |
class func just(t: A) -> Maybe<A> { | |
return Maybe(t) | |
} | |
class func none() -> Maybe { | |
return Maybe() | |
} | |
func isJust() -> Bool { | |
switch value { | |
case .Some(_): return true | |
case .None: return false | |
} | |
} | |
} | |
extension Maybe: Functor { | |
typealias B = Any | |
func fmap(a: Maybe<A>, fn: (A -> B)) -> Maybe<B> { | |
if a.isJust() { | |
let b: B = fn(a.value!) | |
return Maybe<B>.just(b); | |
} else { | |
return Maybe<B>.none() | |
} | |
} | |
} |
mxswd
commented
Jun 6, 2014
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment