List head and tail in Scala

package com.vff.lessons

import scala.collection.GenTraversable
import scala.collection.GenTraversableOnce

/**
 * In functional-style Scala, Collections are processed
 * by splitting a list into its head and tail, where
 * head is the first element and tail is all other elements.
 * <p>
 * This is very useful and often used in Pattern Matching.
 *
 */
object ListHeadAndTail extends App {

  // Create our list.
  val list = List(1, 2, 3, 4, 5, 6)

  // Output the contents of head (1st item) and then tail (rest of the items).
  println("list.head = " + list.head)
  println("list.tail = " + list.tail)

  // Simple recursion.
  def display[A](s: Seq[A]): Unit = {
    // Here is our pattern matching:
    s match {
      // case of an empty list
      case Nil => println("End of list")
      /* match the case where list is not empty -  get first item and 
       * recurse with new list containing the rest of the items - by 
       * default scala collection classes will be immutable.
       */
      case head :: tail => println("Got element - " + head); display(tail)
    }
  }
  
  display(list)
}

Output:

list.head = 1
list.tail = List(2, 3, 4, 5, 6)
Got element - 1
Got element - 2
Got element - 3
Got element - 4
Got element - 5
Got element - 6
End of list
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s