传递所有适用类型的函数 [英] Passing functions for all applicable types around

查看:33
本文介绍了传递所有适用类型的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遵循了此处的建议来定义一个名为square,然后尝试将其传递给调用两次的函数.函数定义如下:

I followed the advice found here to define a function called square, and then tried to pass it to a function called twice. The functions are defined like this:

 def square[T](n: T)(implicit numeric: Numeric[T]): T = numeric.times(n, n)
 def twice[T](f: (T) => T, a: T): T = f(f(a)) 

当调用两次(square, 2)时,REPL会吐出一条错误信息:

When calling twice(square, 2), the REPL spits out an error message:

scala> twice(square, 2)
<console>:8: error: could not find implicit value for parameter numeric: Numeric[T]
       twice(square, 2)
         ^

有人吗?

推荐答案

我不同意这里的所有人,除了 Andrew Phillips.好了,大家到此为止.:-) 问题在这里:

I disagree with everyone here except Andrew Phillips. Well, everyone so far. :-) The problem is here:

def twice[T](f: (T) => T, a: T): T = f(f(a))

您期望,就像 Scala 的新手经常做的那样,Scala 的编译器将 both 参数考虑到 twice 以推断正确的类型.然而,Scala 并没有这样做——它只使用从一个参数列表到下一个参数列表的信息,而不是从一个参数到下一个参数列表.这意味着参数 fa 是独立分析的,而没有知道另一个是什么的优势.

You expect, like newcomers to Scala often do, for Scala's compiler to take into account both parameters to twice to infer the correct types. Scala doesn't do that, though -- it only uses information from one parameter list to the next, but not from one parameter to the next. That mean the parameters f and a are analyzed independently, without having the advantage of knowing what the other is.

这意味着,例如,this 有效:

That means, for instance, that this works:

twice(square[Int], 2)

现在,如果你把它分解成两个参数列表,它也可以工作:

Now, if you break it down into two parameter lists, then it also works:

def twice[T](a: T)(f: (T) => T): T = f(f(a))
twice(2)(square)

所以,基本上,您尝试做的所有事情都是正确的并且应该可以工作,除了您希望一个参数帮助确定另一个参数的类型(正如您编写的那样)).

So, basically, everything you were trying to do was correct and should work, except for the part that you expected one parameter to help figuring out the type of the other parameter (as you wrote it).

这篇关于传递所有适用类型的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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