Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recreating the Functor type in Swift

Tags:

swift

I'm wanting to make the Functor type in Swift as a protocol, but I'm having trouble with the 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 of implies that C is the same as Self, and therefore has the same A. Is there any way to define a generic that is the same type but with a different type parameter?

EDIT: Maybe I should clarify that the goal here is to function like fmap in other functional languages, except self is the in parameter, instead of fmap being a global function that takes an in parameter.

like image 531
Will Fancher Avatar asked Sep 03 '25 04:09

Will Fancher


1 Answers

No, not today. Swift lacks higher-kinded types. It doesn't even have support for first-order types. So as a first step, you'd want to be able to talk about let x: Array<_> where you didn't yet know the type of the contained object. Swift can't handle that. It can't handle generic closures, either. For example:

func firstT<T>(xs: [T]) -> T {
    return xs[0]
}
let ft = firstT // "Argument for generic parameter 'T' could not be inferred"

Those are the simple cases, and Swift's type system already starts falling apart (it can handle it as a function definition, but not as a type). Swift's type system completely falls apart when asked to represent higher-kinded types like Functor.

A little deeper discussion of the issue (but mostly reiterates what I've said here: https://gist.github.com/rnapier/5a84f65886e1ee40f62e)

Note that this isn't specifically a feature so much of "other functional languages." First, Swift isn't really a functional language; it just has some functional features, and second, not all functional languages have this feature (Haskell and Scala, yes, ML and LISP, no). The feature you want is higher-kinded types, and that can exist with or without other functional features.

A nice intro to this is available in section 4.3 Higher-kinded types of Scala for generic programmers. Swift has some very interesting similarities to Scala, so the history of Scala can provide some hints about what might make sense for Swift (Higher-kinded types didn't show up until Scala 2.5).

like image 73
Rob Napier Avatar answered Sep 04 '25 23:09

Rob Napier