更多关于泛型Scala函数

更多关于泛型Scala函数

本文介绍了更多关于泛型Scala函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试在Scala中实现以下Haskell函数(学习你是一个Haskell ...),以便它可以与Int,Double等一起使用。

  doubleUs xy = x * 2 + y * 2 

请注意,这与



这是我的尝试和错误。有人可以解释发生了什么,并提供解决方案。谢谢。

  scala> def doubleUs [A](x:A,y:A)(隐式数字:数字[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)(隐式数字:数字[A]):A = numeric.plus (numeric.times(x,2),numeric.times(y,2))


解决你正在使用 Int 文字 2 ,但scala期待数字键入 A
具有实用功能 - def fromInt(x:Int):T 。这就是你想要使用的,所以用 numeric.fromInt(2) 2 的用法>

  def doubleUs [A](x:A,y:A)(隐式数字:数字[A]):A = 
numeric.plus(numeric.times(x,numeric.fromInt(2)),numeric.times(y,numeric.fromInt(2)))

此外,由于Numeric实例定义了对Ops的隐式转换,您可以导入数字._ ,然后说 x * fromInt(2)+ y * fromInt(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))
解决方案

You are using the Int literal 2 but scala is expecting the Numeric type A.The Scala Numeric API has a utility function- def fromInt(x:Int): T. This is what you want to use, so replace your usage of 2 with numeric.fromInt(2)

def doubleUs[A](x:A,y:A)(implicit numeric: Numeric[A]): A =
  numeric.plus (numeric.times (x, numeric.fromInt (2)), numeric.times (y, numeric.fromInt (2)))

Also, since a Numeric instance defines an implicit conversion to an Ops, you can import numeric._ and then say x * fromInt(2) + y * fromInt(2).

这篇关于更多关于泛型Scala函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 02:47