有关通用 Scala 函数的更多信息
尝试在 Scala 中实现以下 Haskell 函数(来自 Learn You a Haskell...),以便它可以与 Int、Double 等一起使用。
doubleUs x y = x * 2 + y * 2
请注意,这类似于 Scala:如何定义“通用”函数参数?
这是我的尝试和错误。有人可以解释发生了什么并提供解决方案。谢谢。
scala> def doubleUs[A](x:A,y:A)(implicit numeric: Numeric[A]): A = numeric.plus(numeric.times(x,2),numeric.times(y,2))
<console>:34: error: type mismatch;
found : Int(2)
required: A
def doubleUs[A](x:A,y:A)(implicit numeric: Numeric[A]): A = numeric.plus(numeric.times(x,2),numeric.times(y,2))
Trying to implement, in Scala, the following Haskell function (from Learn You a Haskell...) so that it works with Int, Double, etc.
doubleUs x y = x * 2 + y * 2
Note that this is similar to Scala: How to define "generic" function parameters?
Here's my attempt and error. Can someone explain what's happening and offer a solution. Thanks.
scala> def doubleUs[A](x:A,y:A)(implicit numeric: Numeric[A]): A = numeric.plus(numeric.times(x,2),numeric.times(y,2))
<console>:34: error: type mismatch;
found : Int(2)
required: A
def doubleUs[A](x:A,y:A)(implicit numeric: Numeric[A]): A = numeric.plus(numeric.times(x,2),numeric.times(y,2))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
除了 @Dylan 所说的之外,您还可以通过将
Numeric
隐式内容导入范围来使其看起来不那么乏味,如下所示:In addition to what @Dylan said, you can make it look a little less tedious by importing into scope the contents of
Numeric
implicit as shown below:您正在使用
Int
文字2
,但 scala 需要Numeric
类型A
。Scala Numeric API 有一个实用函数 -
def fromInt (x:Int): T
。这就是您想要使用的内容,因此请将2
的用法替换为numeric.fromInt(2)
另外,由于 Numeric 实例定义了到 Ops 的隐式转换,因此您可以可以
import numeric._
然后说x * fromInt(2) + y * fromInt(2)
。You are using the
Int
literal2
but scala is expecting theNumeric
typeA
.The Scala Numeric API has a utility function-
def fromInt(x:Int): T
. This is what you want to use, so replace your usage of2
withnumeric.fromInt(2)
Also, since a Numeric instance defines an implicit conversion to an Ops, you can
import numeric._
and then sayx * fromInt(2) + y * fromInt(2)
.您需要一些隐含的范围:
You need some implicits in scope:
Dylan 本质上回答了,但就其价值而言,让我建议使用上下文绑定语法而不是隐式参数(两者是等效的,并且前者会被编译器自动重写为后者)。
Dylan essentially answered, but for what it's worth, let me suggest to use the context bound syntax instead of the implicit argument (both are equivalent, and the former is automatically rewritten into the latter by the compiler).