Advertisement
DoctorRynerNew

Untitled

Nov 23rd, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.67 KB | None | 0 0
  1. protocol Functor {
  2.     associatedtype A
  3.     associatedtype F: Functor = Self
  4.  
  5.     static func fmap<B> (_ f: @escaping (A) -> B) -> (Self) -> F where F.A == B
  6. }
  7.  
  8. enum Maybe<A> {
  9.     case Nothing
  10.     case Just (A)
  11. }
  12.  
  13. extension Maybe: Functor {
  14.     static func fmap<B>(_ f: @escaping ((A) -> B)) -> (Maybe<A>) -> Maybe<B> {
  15.         return { (functor: Maybe<A>) in
  16.             switch functor {
  17.             case let .Just (x): return .Just (f (x))
  18.             case .Nothing: return .Nothing
  19.             }
  20.         }
  21.     }
  22. }
  23.  
  24. let test1: Maybe<Int>    = Maybe.Just (0)
  25.   , test2: Maybe<String> = Maybe.fmap { String ($0) } (test1)
  26.  
  27. print (test2)
  28.  
  29. // func fmap
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement