Posts

Showing posts from January, 2019

Pattern matching Explained

Image
This is an explanation to the previous blog 1 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 :...