[英]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.