scala.collection.Map[Int,T]的函子

如果可以FunctorMap类型创建一个,我正在尝试查找信息。文档有关于List, 的信息Option,但没有关于我的情况。

你能告诉我是否可以创建一个Functor[Map[Int, T]]

下面我将附上一个类似函子的实现List

trait Functor[F[_]]:
    def map[A, B](list: F[A])(f: A => B): F[B]

given Functor[List] with
    def map[A, B](list: List[A])(f: A => B): List[B] = ???

回答

扩展 Luis 和 Andrey 的答案,使用 Scala 2 和 scala-cats 尝试使用类型别名

import cats.Functor

type MapInt[T] = Map[Int, T]
Functor[MapInt].map(Map(1 -> "woo"))(a => a + "hoo") 
// : MapInt[String] = Map(1 -> "woohoo")

或使用 Scala 2 类型 lambda “暴行”

Functor[({type MapInt[T]=Map[Int, T]})#MapInt].map(Map(1 -> "woo"))(a => a + "hoo")
// : MapInt[String] = Map(1 -> "woohoo")

或使用实物投影仪

Functor[Map[Int, *]].map(Map(1 -> "woo"))(a => a + "hoo")
// : MapInt[String] = Map(1 -> "woohoo")

斯卡斯蒂


关于尝试使用 REPL 来探索这个想法Map是错误的“种类” Functor(如果你从sbt console它开始应该加载它的所有依赖项build.sbt):

scala> import cats.Functor
import cats.Functor

scala> :kind -v Functor
cats.Functor's kind is X[F[A]]
(* -> *) -> *
This is a type constructor that takes type constructor(s): a higher-kinded type.

scala> :kind -v Map
Map's kind is F[A1,+A2]
* -> * -(+)-> *
This is a type constructor: a 1st-order-kinded type.

scala> type MapInt[T] = Map[Int, T]
type MapInt

scala> :kind -v MapInt
MapInt's kind is F[A]
* -> *
This is a type constructor: a 1st-order-kinded type.

注意如何Functor具有高阶种类

(* -> *) -> *
______/
   |
required shape of type argument to Functor

这意味着它需要一个一阶类型的类型构造函数,特别是一个接受单个类型参数的类型构造函数

* -> *
|
only one type argument expected

现在,Map类型构造本身确实有一阶样的预期Functor,但它是错误的元数,因为它有两个类型参数,而不是一

1st arg to Map
|
* -> * --> *
     |
   2nd arg to Map

因此,我们需要一个类型拉姆达修复的第一类参数Map,以Int同时保持第二个类型参数自由这使得它成为了正确的种类和参数数量的类型构造函数Functor

scala> :kind -v MapInt
MapInt's kind is F[A]
* -> *

这是一个高阶类型构造函数的示例,它采用另一个二元元一阶类型构造函数作为其类型参数

trait Foo[F[A, B]]

让我们检查Map现在是否适合而不必使用类型 lambda

scala> trait Foo[F[A, B]]
trait Foo

scala> :kind -v Foo
Foo's kind is X[F[A1,A2]]
(* -> * -> *) -> *
This is a type constructor that takes type constructor(s): a higher-kinded type.

scala> new Foo[Map] {}
val res2: Foo[Map] = $anon$1@589af27e


以上是scala.collection.Map[Int,T]的函子的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>