在Scala中应用函数之前编写函数参数 [英] Writing function parameters before function to be applied in Scala

查看:136
本文介绍了在Scala中应用函数之前编写函数参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以像(parameter1,parameter2)这样的语法应用myFunction 。这里myFunction将应用于给定的参数。具体例子: val myFunction =(a:String)=> A + A + ​​有; hello应用myFunction 应输出hellohellothere。
我知道可以做(parameter1,parameter2)match {case myFunctionWrittenOut} ,所以上面的代码会变成hellomatch { case a:String => a + a +there} 但是在这里你必须写出这个函数:你不能使用一个引用。

我不认为使用标准scala是可能的。但您可以编写一些帮助器方法,使这样的东西可用:

 隐式类Applied1 [T](val t:T )扩展AnyVal {
def applied [R](f:T => R):R = f(t)
}

隐式类Applied2 [T1,T2] (val t:(T1,T2))扩展AnyVal {
def applied [R](f:(T1,T2)=> R):R = f(t._1,t._2)


隐式类Applied3 [T1,T2,T3](val t:(T1,T2,T3))扩展AnyVal {
def applied [R](f:(T1 ,T2,T3)=> R):R = f(t._1,t._2,t._3)
}

// ...和另外19个隐含类:Applied4到Applied22

然后你可以像这样使用它:

  def minus(a:Int):Int = -a 
def plus(a:Int,b:Int):Int = a + b
def plus(a:Int,b:Int,c:Int):Int = a + b + c

scala> 5应用减
res0:Int = -5

scala> (1,2)加
res1:Int = 3

scala> (1,2,3)加
res2:Int = 6

但这可能使用泛型函数或带隐式参数的函数会更复杂一些:

  def mul [T:Numeric](a :T,b:T):T = {
import Numeric.Implicits._
a * b
}

scala> (1.5,2.5)应用(mul(_,_))
res3:Double = 3.75


Is it possible to have syntax like (parameter1, parameter2) applied myFunction. Here myFunction would be applied to the given parameters. Concrete example: val myFunction = (a:String) => a+a+"there"; "hello" applied myFunction should output "hellohellothere". I know it's possible to do (parameter1, parameter2) match {case myFunctionWrittenOut}, so the above would become "hello" match {case a:String => a+a+"there"} but here you have to write out the function: you can't use a reference.

解决方案

I don't think it's possible with standard scala. But you can write some helper methods that would make something like this available:

implicit class Applied1[T](val t: T) extends AnyVal {
  def applied[R](f: T => R): R = f(t)
}

implicit class Applied2[T1, T2](val t: (T1, T2)) extends AnyVal {
  def applied[R](f: (T1, T2) => R): R = f(t._1, t._2)
}

implicit class Applied3[T1, T2, T3](val t: (T1, T2, T3)) extends AnyVal {
  def applied[R](f: (T1, T2, T3) => R): R = f(t._1, t._2, t._3)
}

// ... and 19 more implicit classes: Applied4 to Applied22

And then you can use it like this:

def minus(a: Int): Int = -a
def plus(a: Int, b: Int): Int = a + b
def plus(a: Int, b: Int, c: Int): Int = a + b + c

scala> 5 applied minus
res0: Int = -5

scala> (1, 2) applied plus
res1: Int = 3

scala> (1, 2, 3) applied plus
res2: Int = 6

But this may be a bit more complex to use with generic functions, or functions with implicit arguments:

def mul[T : Numeric](a: T, b: T): T = {
  import Numeric.Implicits._
  a * b
}

scala> (1.5, 2.5) applied (mul(_, _))
res3: Double = 3.75

这篇关于在Scala中应用函数之前编写函数参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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