Scala 编译器无法识别视图绑定
我已经尝试过这行代码
def **[A <% Numeric[A]](l:List[A],m:List[A])=l.zip(m).map({t=>t._1*t._2})
但是在编译时,我收到此错误
error: value * is not a member of type parameter A
def **[A <% Numeric[A]](l:List[A],m:List[A])=l.zip(m).map({t=>t._1*t._2})
当我查看数字特征的源代码时,我看到定义了 *
操作。
我做错了什么?
I've tried this line of code
def **[A <% Numeric[A]](l:List[A],m:List[A])=l.zip(m).map({t=>t._1*t._2})
However on compilation, I get this error
error: value * is not a member of type parameter A
def **[A <% Numeric[A]](l:List[A],m:List[A])=l.zip(m).map({t=>t._1*t._2})
When I look at the source for the Numeric trait, I see a *
op defined.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
Numeric
的实例本身不是数字,而是提供算术运算的对象。例如,Numeric[Int]
类型的对象num
可以将两个整数相加,如下所示:num.plus(3, 5)
结果这个运算的结果是整数 7。对于整数来说,这是非常微不足道的。但是,对于所有基本数字类型,都有一个
Numeric
的隐式实例可用。如果您定义自己的数字类型,则可以提供一种。因此,您应该保留
A
的边界,并添加一个Numeric[A]
类型的隐式参数,用它来进行计算。像这样:当然,
num.times(a,b)
看起来不如a*b
优雅。在大多数情况下,人们可以接受这一点。但是,您可以将值a
包装在支持运算符的Ops
类型的对象中,如下所示:由于方法
mkNumericOps
已声明为>隐式
,您也可以导入它并隐式使用它:The instance of
Numeric
is not a number itself, but it is an object that offers operations to do the arithmetic. For example, an objectnum
of typeNumeric[Int]
can add two integers like this:num.plus(3, 5)
The result of this operation is the integer 7.For integers, this is very trivial. However, for all basic numerical types, there is one implicit instance of
Numeric
available. And if you define your own numeric types, you can provide one.Therefore, you should leave the bounds for
A
open and add an implicit parameter of typeNumeric[A]
, with which you do the calculations. Like this:Of course,
num.times(a,b)
looks less elegant thana*b
. In most of the cases, one can live with that. However, you can wrap the valuea
in an object of typeOps
that supports operators, like this:Since the method
mkNumericOps
is declaredimplicit
, you can also import it and use it implicitly:您还可以通过上下文绑定来解决此问题。使用 这个答案,你可以写:
或者
You can also solve this with a context bound. Using the
context
method from this answer, you can write:or