Partial Function In Scala

Partial Function In Scala

val aFunction = (x: Int) => x + 1

Here aFunction is an instance of Function1[Int, Int] ===== (Int) => (Int) which will accept "any int value" and return with plus 1.

But what if we need aFunction that accepts "a certain part of int" like {1, 2, 3, 4, 5} only, And for the rest of the int value should not be applicable.

Let's create another function aFussyFunction that will throw an exception if the value goes out of {1, 2, 3, 4, 5}.

val aFussyFunction = (x: Int) => {
  if(x >= 1 && x<=5) x + 1
  else throw new FunctionNotApplicableException
}
class FunctionNotApplicableException extends RuntimeException        
val aNicerFussyFunction = (x: Int) => x match
  case x if x >= 1 && x <= 5 => x + 1        

because {1, 2, 3, 4, 5} is a subset of int so this is called a partial function form "Int => Int". why partial? because it accepts only a part of the int domain as an argument.

Scala supports the partial implementation using PartialFunction, and shorthand notation for writing it is following:

val aPartialFunction: PartialFunction[Int, Int] = {
  case x if x >= 1 && x <= 5 => x + 1
}         

{ .... } is a partial function value and equivalent to "aNicerFussyFunction"

Partial functions as we see here will act like proper functions, in the sense that they can be called and used like any other functions.

// here we are calling a apply method of PartialFunction[Int, Int]
val aPartialFunctionResult = aPartialFunction(2)         

At this point, we understand partial functions and their applications. Below are some partial function utilities.

  1. isDefinedAt: This is very useful to figure out whether the PF can run with this argument or not.
  2. lift: PF Can be lifted to a total function returning Option because if PF is not defined for a given argument it will just return None.
  3. orElse: PF will fallback to orElse part in case of Match error.

aPartialFunction.isDefinedAt(10)
val lifted: Int => Option[Int] = aPartialFunction.lift
val pfChain: PartialFunction[Int, Int] = aPartialFunction.orElse{ case 10 => 10 + 1 }        

PF can be used to provide an implementation of total function because PF is a subtype of total function.

val aTotalFunction: Int => Int = { case 1 => 99 }

Because of the above, our favorite HOF like map, flatMap, filter accepts PF as well.

val aMappedList = List(1, 2, 3).map{ case 1 => 42 case 2 => 76 case 3 => 1000 } println(aMappedList) // List(42, 76, 1000) val aErrorMappedList = List(1, 2, 3).map{ case 1 => 42 case 2 => 76 case 5 => 1000 } println(aErrorMappedList) // Caused by: scala.MatchError: 3

Check my GitHub: https://github.com/anish-diliyan/core-scala/blob/master/src/main/scala/fp/PartialFunctionExample.scala

要查看或添加评论,请登录

Anish Kumar的更多文章

  • Understanding Functor

    Understanding Functor

    Functor represents a data structure or context that can be mapped over. It provides a way to apply a function to the…

    1 条评论
  • Monad For Beginners

    Monad For Beginners

    Monads are a fundamental concept in functional programming that represents computations that can be composed and…

  • def vs val To Define Abstract Members

    def vs val To Define Abstract Members

    The short story is that if you want to declare an abstract member in a trait, as a def or val field that may be later…

  • Basic Hierarchy of Scala Cat

    Basic Hierarchy of Scala Cat

  • Sorting in Scala: sorted method

    Sorting in Scala: sorted method

    Sorting in Scala is very similar to sorting in Java like Java's Comparable called Ordered and Java's Comparator called…

  • Anonymous Function: LAMBDA

    Anonymous Function: LAMBDA

    Dream: Use the function as a first-class element like val and var, which can be passed to the function as parameters…

  • Diamond Problem

    Diamond Problem

    The Diamond Problem occurs when a class inherits from two or more parent classes with the same method or field. This…

  • Variance In Scala

    Variance In Scala

    1. All values have a type 2.

  • Match Patterns For Scala Classes

    Match Patterns For Scala Classes

    Pattern matching on case classes is straightforward because it provides extractor patterns out of the box. If we need…

  • Commonly Used Short Hands

    Commonly Used Short Hands

    infix/operator notation: A method with a single parameter can be used as an operator prefix notation: unary_prefix…

社区洞察

其他会员也浏览了