#4 of 99 Problems – count items in a list

This post and the original question are licensed under a Creative Commons Attribution-Share Alike license and all code is released to the public domain.

The easiest way to get the item count for a List in scala is to use the size or length functions provided by List. This answer is an example of writing a function in scala, more specifically a recursive function without side-effects.

Question:
Find the number of elements of a list.
Example:

var result = length(List(1, 1, 2, 3, 5, 8))
println("Result = " + result)

Output: Result = 6

Answer:

object Class04 extends App {

  // Outer function:  
  def length(l:List[Any]):Int = {

    // Inner function:
    @tailrec
    def length(count:Int, l:List[Any]):Int = l match {
      case head::tail => length(count + 1, tail) // recurse
      case Nil        => count                   // empty list so return count
    }

    // call that recursive inner function with initial state:
    length(0, l)
  }

  val result = length(List(1, 1, 2, 3, 5, 8))
  println("Result = " + result)
}

Original Question here: http://aperiodic.net/phil/scala/s-99/

This is an example of a pattern of writing recursive functions – an outer and an inner function. The outer function creates the starting point and calls the inner recursive function which exhaustively iterates, in this case through a 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