#### Overview of this book

Scala Functional Programming Patterns
Credits
Aknowledgement
www.PacktPub.com
Preface
Free Chapter
Grokking the Functional Way
Singletons, Factories, and Builders
Recursion and Chasing your Own Tail
Lazy Sequences – Being Lazy, Being Good
Taming Multiple Inheritance with Traits
Of Visitors and Chains of Responsibilities
Traversals – Mapping/Filtering/Folding/Reducing
Higher Order Functions
Actors and Message Passing
Index

## Getting the nth element of a list

A list holds a certain number of elements. The first element is at index `0`, and the second element at index `1`. If the index is out of range, we get an exception.

We will write a method to find the `nth` element of a list. This method will return an option. If `n` is out of bounds, we will return `None`. Otherwise, we will return `Some(elem)`. Let's look at the code and then a diagram to understand it better:

```import scala.annotation.tailrec
object NthElemOfList extends App {
def nth(list: List[Int], n: Int): Option[Int] = {
@tailrec
def nthElem(list: List[Int], acc: (Int, Int)): Option[Int] = list match {
case Nil => None
case head :: tail => {
if (acc._1 == acc._2)     // 1