Skip to content

Instantly share code, notes, and snippets.

@mxswd
Forked from joshaber/gist:1a3d6af1a81e86fb6322
Last active August 29, 2015 14:02
Show Gist options
  • Save mxswd/b2e7c6a9c3f8ddd67793 to your computer and use it in GitHub Desktop.
Save mxswd/b2e7c6a9c3f8ddd67793 to your computer and use it in GitHub Desktop.
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)?
func fromJust() -> A {
return self.value!()
}
init(_ v: A) {
value = { return 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.fromJust())
return Maybe<B>.just(b);
} else {
return Maybe<B>.none()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment