写我自己的通用地图functioni [英] Writing my own generic map 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 theMap
s. What changes should I make so that it works withMap
s 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 onMap
s always returns aList
even when it makes sense to return aMap
itself. You can avoid that by changingCC[_]
toCC
. (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屋!