Skip to content

Instantly share code, notes, and snippets.

@onmyway133
Forked from naoty/Functor.swift
Created September 26, 2015 17:52
Show Gist options
  • Save onmyway133/343daa72f32237e2879a to your computer and use it in GitHub Desktop.
Save onmyway133/343daa72f32237e2879a to your computer and use it in GitHub Desktop.
import Foundation
struct Box<T> {}
protocol Functor {
typealias A
typealias B
typealias Boxed = Box<B>
func fmap<B>(f: A -> B) -> Boxed
}
extension Array: Functor {
typealias A = T
typealias B = Any
typealias Boxed = [B]
func fmap<B>(f: A -> B) -> Boxed {
return self.map({ f($0) })
}
}
extension Optional: Functor {
typealias A = T
typealias B = Any
typealias Boxed = B?
func fmap<B>(f: A -> B) -> Boxed {
switch self {
case .Some(let value):
return Boxed(f(value))
case .None:
return .None
}
}
}
let n: Int? = 1
let m = n.fmap { x in "\(x)" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment