Playing Functor type in Swift
I want to make Functor type in Swift as a protocol, but I am having problems with type clauses.
protocol Functor {
typealias A
func fmap<
B, C
where
C == Self
C.A == B>
(A -> B) -> C
}
The problem is that C == Self sort implies that C is the same as Self and therefore has the same A. Is there a way to define a generic type that is the same type but with a different parameter type?
EDIT: Perhaps I should clarify that the goal here is to function like fmap in other functional languages, except that self is an in parameter and fmap is a global function that takes an in parameter.
source to share
No not today. Swift lacks high-level types. It doesn't even support first-order types. So, as a first step, you will need to talk about let x: Array<_>
where you didn't know the type of the contained object yet. Swift can't handle it. It also cannot handle common closures. For example:
func firstT<T>(xs: [T]) -> T {
return xs[0]
}
let ft = firstT // "Argument for generic parameter 'T' could not be inferred"
These are simple cases, and Swift's type system is already starting to fall apart (it can handle it as a function definition, but not as a type). The Swift system falls apart completely when asked to represent higher-grade types like Functor.
A little deeper discussion of the problem (but basically repeats what I said here: https://gist.github.com/rnapier/5a84f65886e1ee40f62e )
Note that this is not a feature of many "other functional languages". First, Swift is not really a functional language; it just has some functionality, and secondly, not all functional languages โโhave this functionality (Haskell and Scala, yes, ML and LISP, no). The function you want are higher type types that can exist with or without other functionalities.
A good introduction to this is available in section 4.3. Higher Scala types for generic programmers . Swift has very interesting similarities to Scala, so Scala's history may provide some hints as to what might make sense for Swift (higher-grade types were not mapped until Scala 2.5).
source to share