Higher-kinded types

Higher-kinded types have the ability to reason about generic types with their type parameters as variables. Functors, Monads, and Applicative Functors are higher-kinded types and are not supported natively in the Swift 3.0 type system!

For curious readers, it is recommended to read the Swift Evolution Proposal (https://lists.swift.org/pipermail/swift-evolution/Week-of-Mon-20151214/002736.html) and the Generic manifesto (https://github.com/apple/swift/blob/master/docs/GenericsManifesto.md#higher-kinded-types).

According to the Generic Manifesto, higher-kinded types allow us to express the relationship between two different specializations of the same nominal type within a protocol. For example, if we think of the Self type in a protocol as really being Self<T>, it allows us to talk about the relationship between Self<T> and Self<U> for some other type U. For instance, it could allow the map operation on a collection to return a collection of the same kind but with a different operation, for example:

let intArray: Array<Int> = [1, 2, 3] 
let newArray = intArray.map { String($0) } // produces Array<String>
let intSet: Set<Int> = [1, 2, 3]
let newSet = intSet.map { String($0) } // produces Set<String>

This proposal suggests to use ~= as a similarity constraint to describe a Functor protocol:

protocol Functor { 
associatedtype A
func fmap<FB where FB ~= Self>(f: A -> FB.A) -> FB
}

Here, the map function declaration specifies a function, fmap, on the Self type (where Self is a Functor with associatedtype A) with the type parameter FB, that is the same kind of Functor as Self, with an arbitrarily different A type alias. We will talk about map in detail in the The map function section of this chapter.

As Swift 3.0 does not support higher-kinded types, we are not going to dive deeper in to these topics. We will consider Functor, Monad, and Applicative Functor concepts briefly in upcoming sections and outline their part in Swift functional programming. As these concepts are not very easy to grasp and may not be very practical for most readers, we will not dive deep in to these topics. For curious readers, it is highly recommended to read references such as Swift Functors, Applicatives, and Monads in pictures, which can be found here: http://www.mokacoding.com/blog/functor-applicative-monads-in-pictures/.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset