scala 匿名函数缺少参数类型错误 [英] scala anonymous function missing parameter type error
问题描述
我写了以下内容
def mapFun[T, U](xs: List[T], f: T => U): List[U] = (xs foldRight List[U]())( f(_)::_ )
当我这样做时
def f(x: Int):Int=x*x
mapFun(List(1,2,3), f)
效果很好.但是,我也很想做以下工作
It worked fine. However, I really wanted to make the following work too
mapFun(List(1,2,3), x=>x*x)
它抱怨缺少参数类型".我知道我可以使用柯里化,但是有没有办法仍然使用匿名函数来实现我上面提到的非柯里化定义?
It complains about "missing parameter type". I know that I could use currying, but is there any way to still use anonymous function for non-currying def I had above?
推荐答案
在我看来,因为f"与xs"在同一个参数列表中,你需要提供一些关于 x 类型的信息以便编译器可以解决它.
It seems to me that because "f" is in the same parameter list as "xs", you're required to give some information regarding the type of x so that the compiler can solve it.
在您的情况下,这将起作用:
In your case, this will work:
mapFun(List(1,2,3) , (x: Int) => x * x)
你看到我是如何通知编译器 x 是一个 Int 的吗?
Do you see how I'm informing the compiler that x is an Int?
你可以做的一个技巧"是咖喱 f.如果您不知道什么是柯里化,请查看:http://www.codecommit.com/blog/scala/function-currying-in-scala
A "trick" that you can do is currying f. If you don't know what currying is check this out: http://www.codecommit.com/blog/scala/function-currying-in-scala
你最终会得到一个像这样的 mapFun:
You will end up with a mapFun like this:
def mapFun[T, U](xs: List[T])(f: T => U): List[U] =
(xs foldRight List[U]())( f(_)::_ )
这会起作用:
mapFun(List(1,2,3))(x => x * x)
在最后一次调用中,x 的类型在编译器检查第一个参数列表时解析.
In the last call, the type of x is resolved when the compiler checks the first parameter list.
正如 Dominic 所指出的,您可以告诉编译器您的类型是什么.导致:
As Dominic pointed out, you could tell the compiler what your types are. Leading to:
mapFun[Int, Int](List(1,2,3), x => x * x)
干杯!
这篇关于scala 匿名函数缺少参数类型错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!