Pattern matching Explained

This is an explanation to the previous blog1 relating to the Scala Matching. Most of the thoughts referring to the book "Functional Programming in Scala"2.

For example consider the following Algebraic Data Type MList:

// Singly linked lists
sealed trait MList[+A]
case object MNil extends MList[Nothing]
case class Cons[+A](head:A, tail: MList[A]) extends MList[A]

object MList{ //companion object
  def sum (ints: MList[Int]):Int =
    ints match {
      case MNil => 0
      case Cons(x,xs) => x + sum(xs)
    }

  def apply[A](as: A*): MList[A] =
    if (as.isEmpty) MNil else Cons(as.head, apply(as.tail: _*))

  def append[A](fs:MList[A], ss:MList[A]): MList[A] =
    fs match {
      case MNil => ss
      case Cons(h,t) => Cons(h,append(t, ss))
    }

  //curried way
  def dropWhile[A](l:MList[A])( f:A => Boolean): MList[A] =
    l match {
      case Cons(h,t) if f(h) => dropWhile(t)(f)
      case _ => l
    }
}

val x : MList[Int] = MList()
val y : MList[Int] = MList(1)
val z : MList[Int] = MList(2,1)
val k : MList[Int] = MList(3,2,1)

The output can be described as follows:

scalap

The output of above is

x: MList[Int] = MNil
y: MList[Int] = Cons(1,MNil)
z: MList[Int] = Cons(2,Cons(1,MNil))
k: MList[Int] = Cons(3,Cons(2,Cons(1,MNil)

In the above concept MList(3,2,1) can be visualised in a singly linked list:

scala_pattern_matching-2

Variadic function is a syntatic sugar to explicitly pass the sequence of elements to the List. In the above program, variadic function is apply() which is shown at line# 13. This means that this function has to accept 0 or more arguments. The use of the apply() at line# 17 t0 20 are list literals. The wild card syntax in the line#14 allow us to pass the sequence of elements.

Variable Pattern

List(1,2,3) match {
    case _ => 0
} 

Her the result is 0.

Data Constructor Pattern

List (1,2,3) match {
    case Cons(h, _) => h
}

Here the result is 1

In addition to that you can use the following as well

List (1,2,3) match {
    case Cons(_, t) => t
}

Above result the List(2,3).

List (1,2,3) match {
    case Nil => 0
}

return MatchError at runtime.

REFERENCE


  1. Blog Post Scala Tips: Matching 

  2. Functional Programming in Scala by Paul Chiusano and RĂșnar Bjarnason, Published by Manning Publications, 2014 

Comments

Popular posts from this blog

How To: GitHub projects in Spring Tool Suite

Spring 3 Part 7: Spring with Databases

Parse the namespace based XML using Python