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部分应用函数