Partial functions
A partial function is defined on part of its domain. isDefinedAt says whether a value is inside, apply answers only for one that is, and collect and lift are the two ways a program uses one without asking first. A match with case clauses is the literal of the type.
A function defined in part
The block below is a PartialFunction[(Int, Int), Int]: the guard takes the pairs with a non-zero divisor, and the division answers for those. A pair outside the domain has no value, and the type says so:
partial.scala
val divide: PartialFunction[(Int, Int), Int] =
case (a, b) if b != 0 => a / b
@main def partial(): Unit =
println(divide.isDefinedAt((6, 2)))
println(divide.isDefinedAt((6, 0)))
println(divide((6, 2)))
println(divide.applyOrElse((6, 0), (_: (Int, Int)) => -1))
scala-cli run --server=false partial.scala
true
false
3
-1
isDefinedAt((6, 0)) is false, and divide((6, 0)) would throw a MatchError. applyOrElse takes the default instead, which is the safe call: it answers for every value of the domain of the default.
collect, lift and orElse
collect takes a partial function over a collection and drops what the function does not accept, so a filter and a map become one call. lift turns the partial function into a total one that answers Option, and orElse joins two partial functions into one defined where either is. The type that lift answers is the one the Option, Either and Try lesson takes apart, and collect belongs to the methods the higher-order functions lesson introduces:
collect.scala
@main def collect(): Unit =
val values = List(1, 2, 3, 4, 5, 6)
val even = values.collect { case n if n % 2 == 0 => n * 10 }
println(even)
val strings: PartialFunction[Any, String] = { case s: String => s }
println(List("a", 1, "b").collect(strings))
val positive: PartialFunction[Int, Int] = { case n if n > 0 => n }
println(positive.lift(5))
println(positive.lift(-5))
val fallback = positive.orElse[Int, Int] { case n => -n }
println(fallback(-5))
scala-cli run --server=false collect.scala
List(20, 40, 60)
List(a, b)
Some(5)
None
5
The typed pattern case s: String is the other thing a partial function does well: over a list of Any it keeps the strings and drops the numbers, and the result is a List[String]. That is the pattern a parser uses for a heterogeneous message, and the pattern matching lesson takes the same syntax further.
Автор статьи: Arthur Isaev