写我自己的通用地图functioni [英] Writing my own generic map functioni

查看:167
本文介绍了写我自己的通用地图functioni的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写我自己的通用 map 函数,下面是我想出的:

  def map [A​​,B,CC [X]< ;: Traversable [X],that] 
(xs:CC [A])(f:A = B)
(隐含cbf:CanBuildFrom [CC [_],B,That]):That = {
val b = cbf(xs)
for(a< - xs)
b + = f(a)
b.result
}

这似乎适用于 List Vector ,但不适用于 Map s。我应该做什么变化,以使它与 Map 一起工作?

解决方案

p>你的代码编译和运行很好(注意:我使用Scala 2.9.0.1。你可能想提到你使用的是什么版本的Scala。)



您的 map 函数应用于映射时总是返回 List 即使有意义的是返回一个 Map 本身。您可以通过将 CC [_] 更改为 CC 来避免这种情况。 (相关博文: Scala中的常规快速排序。 )

  def map [A​​,B,CC< ;: Traversable [A],That] 
(xs: CC)(f:A => B)
(隐含cbf:CanBuildFrom [CC,B,That]):that = {
val b = cbf(xs)
for < - xs)
b + = f(a)
b.result
}


b $ b

但是你需要在调用它时显式地对这个函数进行类型化注释,这是有点伤心。

  val xs = Map(45→32,11→9)
map [(Int,Int),(Int,Int),Map [Int,Int],Map [Int,Int]]映射(45-> 32,11-> 9))(标识)
//给出Map(45-> 32,11-> 9)



必须有一些方法来避免这种丑陋的类型注释,但我不知道。


I am trying to write my own generic map function and following is what I have come up with:

def map[A, B, CC[X] <: Traversable[X], That]             
       (xs: CC[A])(f: A => B)
       (implicit cbf: CanBuildFrom[CC[_], B, That]): That = {
  val b = cbf(xs)
  for (a <- xs)
    b += f(a)
  b.result
}

This seems to work with List, Vector, but not with the Maps. What changes should I make so that it works with Maps too?

解决方案

Your code compiles and runs just fine (Note: I am using Scala 2.9.0.1. You might want to mention what version of Scala you are using.)

However your map function when applied on Maps always returns a List even when it makes sense to return a Map itself. You can avoid that by changing CC[_] to CC. (Related blog post: A Generic Quicksort in Scala.)

def map[A, B, CC <: Traversable[A], That]
       (xs: CC)(f: A => B)
       (implicit cbf: CanBuildFrom[CC, B, That]): That = {
  val b = cbf(xs)
  for (a <- xs)
    b += f(a)
  b.result
}

But you need to explicitly type-annotate this function when invoking it, which is a bit sad.

val xs = Map(45 -> 32, 11 -> 9)
map[(Int, Int), (Int, Int), Map[Int, Int], Map[Int, Int]](Map(45 -> 32, 11 -> 9))(identity)
// gives Map(45 -> 32, 11 -> 9)

There must be some way to avoid this ugly type annotation, but I am not aware of it.

这篇关于写我自己的通用地图functioni的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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