Skip to content

Instantly share code, notes, and snippets.

@joshaber
Created June 5, 2014 21:20
Show Gist options
  • Save joshaber/1a3d6af1a81e86fb6322 to your computer and use it in GitHub Desktop.
Save joshaber/1a3d6af1a81e86fb6322 to your computer and use it in GitHub Desktop.
Functor
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
Copy link

mxswd commented Jun 6, 2014

var value: (() ->  A)?

init(_ v: A) {
  value = { return v }
}

func fromJust() -> A {
  return self.value!()
}

...

let b: B = fn(a.fromJust())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment