A bit of Scala!

Hi all!

I was very busy lately and wasn’t able to post anything here, even though i had some algorithmic stuff ongoing and a couple of interesting problems i may share with you in the near future.

Today I decided to post a very small piece of Scala code which express very clearly some basic idea behind the completely new programming idiom i found in Scala. I think many of you C++ Engineers may share the same feeling of being lost when handling Scala, unless you had some previous Functional programming experience 🙂

def create_list(delim:Int,arr:List[Int]):List[Int] = {
     def solve(data:List[Int]):List[Int] = data match {
         case x::xs => {
                  List.fill(1)(x) ::: solve(xs)
             else solve(xs)
         case _ => List()

This piece of code takes a List of Ints and create a new list by extracting only the elements which are smaller than delim from the input and then return that List. Again, nothing which may impress you if you have any Functional programming experience, but if you haven’t, then you may wondering what the hell is going on!!

First of all, we do not have return statement, return’s are not required in Scala unless you know what you’re doing. A function will return the value of the last statement of the body code. The code of create_list is a little over engineered in order to show two important facts:

  1. A function eventually return something, in this case as declared in the function signature a List[Int]
    • You may express the will to force a given return type by using the return keyword, but this is considered nasty!
  2. You may envelope many function one into another, and recursively perform some computation on the input data!

In C++ we are used to have return statement, and clear variable manipulation, here we have some implicit things going on and a more critical understanding of what is happening in needed, sometime variables or names are not declared explicitly.

In create_list we have x and xs which are the head and the tail of the list begin processed in the pattern matchin –match– function, the case statement basically checks whether the list is empty or if still there’s something to process, in which case calls recursively create_list otherwise return the builded list.

The return List of solve is created concatenating –::: operator– the current element and the List returned by a recursive call to itself. This is a basic recursion pattern no more explaination needed i guess.



Leave a Reply