Atif Shahzad
Atif Shahzad

Reputation: 163

Scala : Code for pattern match

I have a code written by some one else. Can you help me to understand this piece of code?

 def sameCodeForTwoYears(list: List[(LocalDate, String)]):  List[(LocalDate, String)] = {
 list match {
  case x :: Nil => List.empty
  case x :: xs => if (xs.head._1.minusYears(2).isAfter(x._1) && x._2 == xs.head._2) {
    List(x, xs.head)
  } else sameCodeForTwoYears(xs)
  case Nil => List.empty
  }
}

Upvotes: 2

Views: 140

Answers (2)

Yuval Itzchakov
Yuval Itzchakov

Reputation: 149608

Scalas List[+T] is an abstract class, implemented by two concrete classes:

  1. Nil - Representing an empty list
  2. Cons (::) - Represents a linked list with a head of type T and a tail of type List[+T].

The pattern match you see here basically represents these two constructs. Let's do a by case analysis:

case x :: Nil => List.empty

Means "if head is non empty and tail is an empty list, return an List.empty", which returns an empty list.

case x :: xs => if (xs.head._1.minusYears(2).isAfter(x._1) && x._2 == xs.head._2) {
List(x, xs.head)

Means "if both head and tail are non-empty". The predicates following the match basically look into the tuple stored inside the List[(LocalDateTime, String)] where _1 represents the first element and _2 represents the second element. We dig a little deeper into the meaning if the condition:

xs.head._1.minusYears(2).isAfter(x._1)

Means "take the first element from tail (xs, it's head), look into the first element in the tuple and subtract it by 2 years. If the first element in xs tuple (which is a LocalDateTime) is after that time.

And

x._2 == xs.head._2

Means "look into the heads (x) second element, which is a String, and match it to the next element which is the tails (xs) first element (xs.head) and match both strings for equality.

Finally:

case Nil => List.empty

Means "if the list is empty", return an empty list.

Upvotes: 2

A Spoty Spot
A Spoty Spot

Reputation: 746

See: http://docs.scala-lang.org/tutorials/tour/pattern-matching.html and http://joda-time.sourceforge.net/apidocs/org/joda/time/LocalDate.html

It basically take in a list of a date: LocalDate and and code: String. If this list is empty or contains one element it returns an empty list. If neither of the above apply it looks at the first two elements of the list, we shall call them y and z. If y's is after (z's date - 2 years) and y and z's codes are the same it returns a list of y and z.

Upvotes: 0

Related Questions