Scala 映射函数签名的解释? [英] Explanation of Scala map function signature?

查看:51
本文介绍了Scala 映射函数签名的解释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码将函数应用于 Int 列表,并将选项列表中的每个值设置为 4 :

This code applies a function to List of Ints and sets each value in the List of Option with value 4 :

  val l = List(1,2,3,4,5)                         //> l  : List[Int] = 
  val v = 4                                       //> v  : Int = 4
  def g(v:Int) = List(v-1, v, v+1)                //> g: (v: Int)List[Int]
 l map (x => {f(x);})                            //> res0: List[Option[Int]] = List(Some(4), Some(4), Some(4), Some(4), Some(4)) 

地图签名:

   def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That = {

既然 B 是第一个类型参数(在 map[B, That] 中),这是否意味着它的类型化为前缀操作数 'l'(列表)?

Since B is the first type parameter (in map[B, That]) does this mean its typed to the prefix operand 'l' (List) ?

A"是如何输入的?scala 编译器是否会以某种方式检查 List 'l' 中的类型并推断其类型为 Int ?

How is 'A' typed ? Does the scala compiler somehow check the type within the the List 'l' and infer that its of type Int ?

那个"是如何输入的?

推荐答案

List[A]map 的简单签名是

The simple signature for map in a List[A] is

def map[B](f: (A) ⇒ B): List[B]

这意味着

  • A 由实际列表的类型参数决定
    • Int 用于示例列表 l
    • A is determined by the type parameter of the actual list
      • Int for the example list l
      • Option[Int] 用于示例函数 f: Int ->选项[Int]
      • Option[Int] for the example function f: Int -> Option[Int]

      扩展签名是

      def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That
      

      存在以便您可以在可以以某种方式遍历的容器之间进行一般映射,即使目标 traversable 具有与原始形式不同的形式.

      which exist so that you can generically map between containers that can be traversed in some way, even when the target traversable has a different form than the original.

      一个具体的例子是遍历一个 Map 作为 Pairs 的容器,具有生成单个值的映射函数.所结果的traversable 不再是 Map,所以 CanBuildFrom 隐式参数用于查找可用表示"结果对象.

      A specific example is traversing a Map as a container of Pairs, with a mapping function that produces single values. The resulting traversable is not a Map anymore, so the CanBuildFrom implicit parameter is used to find "available representations" for the resulting object.

      在这个签名中我们有

      • Repr 为原始遍历容器的类型
      • B 作为包含值的目标类型,如在简化签名中
      • that 作为目标容器的类型,由在调用站点具有正确类型的 CanBuildFrom 的隐式存在决定
      • Repr as the type of the original traversed container
      • B as the target type of the contained values, as in the simplified signature
      • That as the type of the target container, determined by the implicit existence of a CanBuildFrom with the correct types at call site

      这篇关于Scala 映射函数签名的解释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆