5 ms·
That doesn't actually work, because you're limiting the return type of the method in the implementation of the functor. So by implementing that protocol, you co
by afthonos 12y ago
That doesn't actually work, because you're limiting the return type of the method in the implementation of the functor. So by implementing that protocol, you could have one mapping from Int to String (say), but not another from Int to Double.
Put another way, you need to specify FunctorResult at implementation time, and the whole point is to only have to specify it at call time.
- jmah 12y agoThis code works: let d = [1: 1, 2: 2, 3: 3] let intToInt = d.map { $0 + 1 } var IntToString = d.map { String($0) }
- afthonos 12y agoThe code works, but the type of the generic is not guaranteed at compile time. FunctorResult could be anything at all. There is no compile-time obligation for the code to return a Dictionary<KeyType, P>. The more canonical example of a Functor is really the Optional. The mapping method for an optional looks like this: func fmap(f: A -> B) -> Optional<B> { switch self { case Some(let a): return Some(f(A)) case None: return None } } However, with your protocol, I can define the mapping function for the Optional as: func fmap(f: A -> B) -> B[] { switch self { case Some(let a): return [f(A)] case None: return B[]() } } This would pass the type-checker, but is not what a Functor does.