How to declare protocol for HKT in swift?

Viewed 405

In Haskell, when using typeclass, it is easy to declare constraint of its' instances' type kind.

class Functor (f :: * -> *) where
  ...

* -> * represents HKT (Higher-Kinded Types), this means any type conforming to Functor must be a HKT.

How can I achieve this with Swift's protocol ?

1 Answers

Swift does not support HKT as a type form natively, but you can simulate the constraint with a trick of associatedtype:

public protocol Functor {
    /// (* -> *)
    associatedtype FA: Functor = Self
    /// *
    associatedtype A
    /// fmap
    func fmap<B>(_ f: ((A) -> B)) -> FA where FA.A == B
}

And conformance example:

enum Maybe<A> {
    case just(A)
    case nothing
}

extension Maybe: Functor {
    func fmap<B>(_ transform: ((A) -> B)) -> Maybe<B> {
        switch self {
        case .nothing:
            return .nothing
        case .just(let v):
            return .just(transform(v))
        }
    }
}
Related