Scala 函数式编程_部分应用函数_Partially Applied Functions
2019獨角獸企業重金招聘Python工程師標準>>>
Scala 函數式編程部分應用函數或函數的部分應用
和其他遵循函數式編程范式的語言一樣,Scala 允許部分應用一個函數。 調用一個函數時,不是把函數需要的所有參數都傳遞給它,而是僅僅傳遞一部分,其他參數留空; 這樣會生成一個新的函數,其參數列表由那些被留空的參數組成。(不要把這個概念和偏函數混淆)
何為部分應用函數?
Partially Applied Function:
A function that’s used in an expression and that misses some of its arguments.
For instance, if function f has type Int => Int => Int, then f and f(1) are partially applied functions.
?
A partially applied function is an expression in which you don’t supply all of the arguments needed by the function. Instead, you supply some, or none, of the needed arguments.
缺失的是函數需要的參數
scala>?def?sum(a:?Int,?b:?Int,?c:?Int)?=?a?+?b?+?c sum:?(a:?Int,?b:?Int,?c:?Int)Int scala>?sum?_ res1:?(Int,?Int,?Int)?=>?Int?=?<function3> scala>?val?a?=?sum?_ a:?(Int,?Int,?Int)?=>?Int?=?<function3> scala>?a(1,2,3) res2:?Int?=?6代碼如下,
object?PartialApplyFuncTest?{def?calc(a:?Int,?b:?Int,?c:?Int)?=?a?+?b?-?cdef?main(args:?Array[String])?{val?list?=?List(1,?2,?3,?4,?5)list.foreach(println?_)?//缺失所有參數(只有一個)list.foreach(println(_))?//缺失一個參數(println實際上就一個參數)//?list.foreach(println?_)等價于list.foreach(x?=>?println?x)//?list.foreach(println(_)),是否等價于list.foreach(println?_)?等價val?print?=?println(_:?Int)?//調用print時,需要給定一個參數list.foreach(print)//如下通過_定義的部分應用函數,必須為_指定類型//val?s0?=?calc?//編譯錯,參數個數缺失或者根本不存在無參的calc函數val?s00?=?calc(1,?2,?4)?//參數足夠,直接調用val?s1?=?calc(_:?Int,?2,?3)?//缺失第一個參數val?s2?=?calc(_:?Int,?_:?Int,?3)?//缺失第一個,第二個參數val?s3?=?calc(_:?Int,?2,?_:?Int)?//缺失第一個,第三個參數val?s4?=?calc(_:?Int,?_:?Int,?_:?Int)?//缺失第一個,第二個和第三個參數val?s5?=?calc?_?//所有的參數列表都缺失(缺失第一個,第二個和第三個參數)println(s1(10))println(s2(20,?30))println(s3(10,?20))println(s4(3,?2,?1))println(s5(1,?3,?5))//apply語法,s5(1,3,5)等價于s5.apply(1,3,5),apply方法將參數列表發送給s5指向的函數,進行調用val?f?=?(_:?Int)?+?(_:?Int)println(f(1,?2))} }============END============
轉載于:https://my.oschina.net/xinxingegeya/blog/406058
總結
以上是生活随笔為你收集整理的Scala 函数式编程_部分应用函数_Partially Applied Functions的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 互联网+激发连锁酒店竞争意识 OTA遭遇
- 下一篇: CentOS防火墙操作实例(启动、停止、