Skip to content

Instantly share code, notes, and snippets.

@jeffh
Created October 13, 2014 19:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeffh/54755df5467b3de7dfb7 to your computer and use it in GitHub Desktop.
Save jeffh/54755df5467b3de7dfb7 to your computer and use it in GitHub Desktop.
Functors
import Foundation
protocol Mappable {
typealias T
func fmap<M: Mappable>(f: (T) -> M) -> M
}
extension Array : Mappable {
func fmap<M: Mappable>(f: (Array<T>) -> M) -> M {
return f(self)
}
}
class MyBox<T> : Mappable {
var value: T
init(_ value: T) {
self.value = value
}
func fmap<M : Mappable>(f: (T) -> M) -> M {
return f(value)
}
}
func fmap<T, Mt: Mappable, Mu: Mappable where Mt.T == T>(value: Mt, f: (T) -> Mu) -> Mu {
return value.fmap(f)
}
let cat = "my cat"
let box = MyBox(cat)
fmap(box) { MyBox($0 + " other stuff") }
fmap([1, 2, 3]) { arr in [2, 3, 4] }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment