What is a kind projector

好久不见. 提交于 2020-06-22 12:16:08

问题


I've been digging into FP and everything that surrounds it, and I found the concept of kind projector written somewhere, without details nor explanations.

The only thing I found was this github project, and I'm starting to think if it was referring to this particular project, or to some generic concept in FP?

So, what is a kind projector? Why is it useful? (if possible, can you provide examples, resources, etc?)


回答1:


This is indeed just a slightly awkward name for the specific plugin for the Scala compiler you linked to. I don't think it has any significance to itself, but it kind of fits its purpose.

What the plugin does is to provide an alternative syntax to Scala's usual workaround for type lambdas, which uses a language feature called type projections.

Say you wanted to implement Functor for Either. Now, Functor requires kind * -> *, whereas Either has kind * -> * -> *. So we need to first fix the first argument, and can then provide the implementation for the partially applied type constructor. The only way you can do this in "regular" Scala is this:

implicit def eitherIsFunctor[A]: Functor[{type λ[X] = Either[A, X]}#λ] = { ... }

where {type λ[X] = Either[A, X]} is an anonymous structural type, which is only immediately used to "project out" λ, the type we actually want. In Haskell, you could just say

instance Functor (Either a) where ...

where Either is partially applied (and a is quantified over automatically).

The plugin allows one to replace the projection with something that looks more like a usual partial application in Scala, namely Either[A, ?], instead of the hardly understandable {type λ[X] = Either[A, X]}#λ (and also provides general type lambdas, I think, always by converting them down to anonymous types and projections).




回答2:


Scala 3 provides native type lambdas which are no longer based on type projection

A type lambda such as [X] =>> F[X] defines a function from types to types.

For example,

trait Functor[F[_]]

new Functor[Either[String, Int]] {}                   // error
new Functor[({ type λ[X] = Either[String, X] })#λ] {} // Scala 2 type lambda based on type projection
new Functor[λ[X => Either[String, X]]] {}             // kind projector type lambda
new Functor[Either[String, *]] {}                     // kind projector type lambda
new Functor[[X] =>> Either[String, X]] {}             // Scala 3 type lambda         

Also, there exists a proposal SIP: Underscore Syntax for Type Lambdas #5379 such that

Functor[Either[String, _]] // equivalent to Functor[[X] =>> Either[String, X]]


来源:https://stackoverflow.com/questions/39905267/what-is-a-kind-projector

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!