Skip to content

Cryptic pattern matching example #76

@Dinduks

Description

@Dinduks

Hi,

Imagine someone who has never done Scala or a similar language before, visiting the scala-lang site. Then he stumbles upon this:

// Define a set of case classes for representing binary trees.
sealed abstract class Tree[+A]
case class Node[+A](elem: A, left: Tree[A], right: Tree[A]) extends Tree[A]
case object Leaf extends Tree[Nothing]

// Return the in-order traversal sequence of a given tree.
def inOrder[A](t: Tree[A]): List[A] = t match {
  case Node(e, l, r) => inOrder(l) ::: List(e) ::: inOrder(r)
  case Leaf          => List()
}

Pattern matching can be explained more easily, with classes or lists for example.

That example could be changed to something similar to:

list match {
   case Nil => "empty"
   case 'a' :: tail => "starting by 'a'"
   case (head:Int) :: _ if head > 3 => "starting by an int greater than 3"
   case (head:Int) :: _ => "starting by an int"
   case _ => "whatever"
}

Taken from: http://matt.aimonetti.net/posts/2012/09/20/what-is-scala-pattern-matching/

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions