The typical efficient implementation of a protocol (aka an interface) is a vtable - an array of pointers to functions. When you instantiate a generic in a statically compiled language, that usually clones the body of the generic thing (method or type) with references to the generic parameters replaced with the type arguments; and the new, cloned body is handed off to codegen.
But if you instantiate via a protocol reference, the compiler doesn't statically know the implementation of the thing you're trying to call - it can't see the body of code to clone. It's an indirect function call through a variable, and without a restricted language, analyzing it quickly runs into the halting problem.
With runtime code generation, the problem can be solved with sufficient magic - the runtime can rewrite as necessary. That's how .NET implements this.
Alternatively, if the body of each generic method is compiled using some form of dynamic dispatch - e.g. every operation on a value whose type is a generic parameter is done via an table of function pointers, and this table is passed into the generic method at the point of every call - then it can work, at some cost in speed. Haskell works like this, AIUI.
Java does it even more simply, with full-fat dynamic dispatch - all generic parameters turn into Object, and method bodies get runtime casts inserted as necessary.
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.
let d = [1: 1, 2: 2, 3: 3]
let intToInt = d.map { $0 + 1 }
var IntToString = d.map { String($0) }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.The third problem a work around exists for: remove the default argument. If you want an empty init, provide one.
Sure it is buggy, but you can express these programs.