繁体   English   中英

理解高阶函数的scala语法

[英]Understanding the scala syntax about high order function

我是 scala 的新手,我需要更具体地说明 sampleFunc val 以下代码片段的情况:

val sampleFunc: Seq[Row] => (Int, Long, Boolean, Row, String) = (mem: Seq[Row]) => {
                                //some code
                      (a1,b1,c1,d1,e1) // returning the value
                  }

spark.udf.register("sampleUDF", udf(sampleFunc,
  StructType(
    Seq(
      StructField(a, IntegerType),
      StructField(b, LongType),
      StructField(c, BooleanType),
      StructField(d, StructType(schema.fields)),
      StructField(e, StringType)
    )
  )))

谢谢。

好吧,我看到在代码片段中使用了Spark ,但让我们忽略这一点,看看sampleFunc 所以一切都很简单:接下来的宪法声明函数本身:

val sampleFunc: Seq[Row] => (Int, Long, Boolean, Row, String) = ...

其中Seq[Row]函数参数类型和(Int, Long, Boolean, Row, String)函数结果。 换句话说,您创建了Function1[Seq[Row], (Int, Long, Boolean, Row, String)]类型的变量

如果你愿意,然后去函数体或实现

... = (mem: Seq[Row]) => {
                                //some code
                      (a1,b1,c1,d1,e1) // returning the value
                  }

其中mem是声明函数参数类型的变量,它应该是相同类型或扩展函数声明类型中使用的类型。 (函数参数是协变的。请参阅另一个很好的 SO 帖子的更多示例: 为什么 Function[-A1,...,+B] 不允许任何超类型作为参数?

=>语句表示在它进入函数体之后。

如果您有更多Java背景或任何其他命令式语言背景,也可以通过方法方式实现:

def sampleFunc(mem: Seq[Row]): (Int, Long, Boolean, Row, String) =  {
  //some code
  (a1,b1,c1,d1,e1) // returning the value
}

希望这可以帮助!

//<-value name-> <-------------- value type-------------------->   <--------------implementation ----------------------->
//              <-arg type-> <-----result type --------------->   <-function argument->   <----func implementation ---->
val  sampleFunc:  Seq[Row]  => (Int, Long, Boolean, Row, String) = (mem: Seq[Row])      => { /*...*/; (a1,b1,c1,d1,e1) }


//same written differently:
//<-value name-> <-------------- value type------------------------------>   <-------implementation ----------->
val sampleFunc: Funtion1[Seq[Row], Tuple5[Int,Long, Boolean, Row, String]] = {mem => /*...*/; (a1,b1,c1,d1,e1)}
  • 值名称:这里没有什么特别的。 只是代码中的另一个val
  • 值类型:它很长但很简单。 它是Function1类型,它接受Seq[Row]并返回Tuple5[Int, Long, Boolean, Row, String] 这只是 Scala 更好的语法。
  • 实现:我们正在使用=>语法创建采用Seq[Row]函数。 这里也没什么特别的。

如果您对 Tuple5 工厂方法调用进行 desuger,可能更容易理解:

val sampleFunc: Seq[Row] => Tuple5[Int, Long, Boolean, Row, String] = 
    (mem: Seq[Row]) => Tuple5(a1,b1,c1,d1,e1)

如果你更进一步,用Function1替换类型中的=> ,你会得到:

Function1[Seq[Row], Tuple5[Int, Long, Boolean, Row, String]]

这意味着sampleFunc是一个函数,它接受一个Seq[Row]类型的参数并返回一个Tuple5[Int, Long, Boolean, Row, String]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM