@rkenmi - Square each element of a Scala list

Square each element of a Scala list


There are two practical ways to square each element of a list.

Square each element of a Scala list


Back to Top

Updated on June 10, 2017

There are two practical ways to square each element of a list, and return the new list. For example, if we input a List(5, 10), we should have a List(25, 100).

Method 1: Pattern Matching

def squareList(xs: List[Int]): List[Int] = xs match {  
    case Nil        =>  xs
    case y :: ys     =>  y * y :: squareList(ys)
}

If xs is empty, case Nil will trigger, simply returning the list that was passed in to squareList.
If xs is not empty, xs will be split as the head and the tail, or y and ys respectively. We mathematically square y by multiplying it with another y and concatenate it to a recursively called squareList with the remaining tail passed into it. Basically, this process will repeat itself for each element in xs until the tail gets shorter and shorter until it becomes Nil. By that point, it will just return xs or equivalently in this case, Nil.

Method 2: Mapping

def squareList(xs: List[Int]): List[Int] = xs map (x => x * x)  

In Lists, there exists a method called map which happens to be a very handy method. This is a very simple and straightforward 1-line function that is much more readable than Method 1. xs simply maps a function passed into it and applies it to every x in xs. x would be an element of type Int in this case, since xs is a list of type Int.


Article Tags:
Scalapattern matchingmap