Created
October 13, 2014 19:24
-
-
Save jeffh/54755df5467b3de7dfb7 to your computer and use it in GitHub Desktop.
Functors
This file contains 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
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