scala部分應用函數
Scala部分功能 (Scala partial functions)
A partial function is a function that returns values only for a specific set of values i.e. this function is not able to return values for some input values. This function is defined so that only some values are allowed in the processing of the code. Like in the case of division by 0, we need to restrict the division to avoid errors.
局部函數是僅針對一組特定值返回值的函數,即該函數無法為某些輸入值返回值。 定義此函數的目的是在處理代碼時僅允許某些值。 就像被0除的情況一樣,我們需要限制除法以避免錯誤。
These are inconsistent functions of Scala programming language and in some cases, they can be of great use.
這些是Scala編程語言的不一致功能,在某些情況下,它們可能會很有用。
The implementation of partial functions in Scala needs other methods too. The methods that are used for implementation are apply() and isDefinedAt(). Also, you use the case statements to implement it.
Scala中部分功能的實現也需要其他方法。 用于實現的方法是apply()和isDefinedAt() 。 另外,您使用case語句來實現它。
The apply() method is used to show the application of a function.
apply()方法用于顯示函數的應用。
The isDefinedAt() method is used to check if the values are in the range of function or not.
isDefinedAt()方法用于檢查值是否在函數范圍內。
Syntax:
句法:
var function_name = new PartialFunction[input_type, return_type]
Example 1:
范例1:
Implementing partial function using isdefinedat() and apply() methods.
使用isdefinedat()和apply()方法實現部分功能 。
object MyObject
{
val divide = new PartialFunction[Int, Int]
{
def isDefinedAt(q: Int) = q != 0
def apply(q: Int) = 124 / q
}
def main(args: Array[String])
{
println("The number divided by 12 is " + divide(12))
}
}
Output
輸出量
The number divided by 12 is 10
Example 2:
范例2:
Implementation of partial function using orElse statement.
使用orElse語句實現部分功能 。
object MyObject
{
val Case1: PartialFunction[Int, String] =
{
case x if (x % 3) != 0 => "Odd"
}
val Case2: PartialFunction[Int, String] =
{
case y if (y % 2) == 0 => "Even"
}
val evenorodd = Case1 orElse Case2
def main(args: Array[String])
{
var x= 324
println("The number "+x+" is "+evenorodd(x))
}
}
Output
輸出量
The number 324 is Even
Example 3:
范例3:
Implementation of partial function using andThen statement.
使用andThen語句實現部分功能 。
object MyObject
{
def main(args: Array[String])
{
val operation1: PartialFunction[Int, Int] =
{
case x if (x%4)!= 0=> x*42
}
val operation2=(x: Int)=> x/3
val op = operation1 andThen operation2
println("Initial value is 34\t and the value after operations is "+op(34))
}
}
Output
輸出量
Initial value is 34 and the value after operations is 476
翻譯自: https://www.includehelp.com/scala/partial-functions.aspx
scala部分應用函數