-
-
Save mxswd/b2e7c6a9c3f8ddd67793 to your computer and use it in GitHub Desktop.
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)? | |
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