Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare protocol for HKT in swift?

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 ?

like image 714
duan Avatar asked Oct 20 '18 12:10

duan


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))
        }
    }
}
like image 156
duan Avatar answered Oct 11 '22 04:10

duan