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
?
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))
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With