我正在尝试编写通用的加权平均函数.我想放宽对值和重量相同类型的要求.即,我想支持说:(value:Float,weight:Int)和(value:Int,weight:Float)参数的序列而不仅仅是:(value:Int,weight:Int)
为此,我首先需要实现一个带有两个通用数值并返回其产品的函数.
def times[A: Numeric, B: Numeric](x: B, y: A): (A, B) : ??? = {...}
Run Code Online (Sandbox Code Playgroud)
编写签名并考虑返回类型,让我意识到我需要为Numerics定义某种层次结构来确定返回类型.即x:Float*y:Int=z:Float,x:Float*y:Double=z:Double.
现在,数字类定义操作plus,times等只为同一类型的参数.我想我需要实现一个类型:
class NumericConverter[Numeirc[A],Numeric[B]]{
type BiggerType=???
}
Run Code Online (Sandbox Code Playgroud)
这样我就可以把我的时间函数写成:
def times[A: Numeric, B: Numeric](x: B, y: A): (A, B) :
NumericConverter[Numeirc[A],Numeric[B]].BiggerType= {...}
Run Code Online (Sandbox Code Playgroud)
并将"较小的类型"转换为"较大的类型"并将其转换为times().
我是在正确的轨道上吗?我将如何"实施" BiggerType?
显然我做不了类似的事情:
type myType = if(...) Int else Float
Run Code Online (Sandbox Code Playgroud)
因为它是动态评估的,所以它不起作用.
我知道我可以使用Scalaz等来做这个,但这是一个学术练习,我想了解如何编写一个静态返回基于参数类型的类型的函数.
如果有更简单的方法,请随时告诉我.
更新:
这就是我想出来的.
abstract class NumericsConvert[A: Numeric,B: Numeric]{
def AisBiggerThanB: Boolean …Run Code Online (Sandbox Code Playgroud) 通常,我们可以采用任何数字类型的任何值,然后将其除以任何数字类型的任何非零值,然后得出合理的结果。
212.7 / 6 // Double = 35.449999999999996
77L / 2.1F // Float = 36.666668
Run Code Online (Sandbox Code Playgroud)
我发现的一个例外是,我们不能将a BigInt与分数类型(Float或Double)混合使用。
但是,在泛型领域中,Integral和Fractional类型之间存在这种有趣的区别。
// can do this
def divideI[I](a: I, b: I)(implicit ev: Integral[I]) = ev.quot(a,b)
// or this
def divideF[F](a: F, b: F)(implicit ev: Fractional[F]) = ev.div(a,b)
// but not this
def divideN[N](a: N, b: N)(implicit ev: Numeric[N]) = ev.???(a,b)
Run Code Online (Sandbox Code Playgroud)
尽管我对这是为什么感到好奇,但真正的问题是:是否有某种解决方法可避免此限制?
我正在尝试为Post请求编写测试
这是我的代码:
val request = CreateLinkRequest(token = Some(validToken),billing_ref_id = Some("123"), store_id = Some("123"), agent_id = Some("123"))
val endPoint = Uri(this.serverRootUrl + "path").toString
val post = Post(endPoint, request)
val pipeline = jsonAsStringPipeline(post)
val responseContents = Await.ready(pipeline, atMost = callMaxWaitDuration)
Run Code Online (Sandbox Code Playgroud)
但这不编译,我不断收到此错误:
Error:(156, 20) could not find implicit value for evidence parameter of type spray.httpx.marshalling.Marshaller[CreateLinkSpec.this.CreateLinkRequest]
val post = Post(endPoint, request)
^
Error:(156, 20) not enough arguments for method apply: (implicit evidence$1:
spray.httpx.marshalling.Marshaller[CreateLinkSpec.this.CreateLinkRequest])spray.http.HttpRequest in class RequestBuilder.
Unspecified value parameter evidence$1.
val post = Post(endPoint, …Run Code Online (Sandbox Code Playgroud)