Funtional programming with Scala

My first impression of scala is that it’s too verbose. Thing that could be done in may be 1 line in haskell and 2 lines in erlang takes around 5-10 lines(Might not look like a big difference for 1 line but production codes easily span thousands of line even with the most expressive languages and here the factor is of 5). Anyways, I am still new so might not be my place to judge it.

Here goes implementation of some functions / practice problems in scala.

1. Pascal triangle such that pascal(r,c) such function return value at rth row and cth column

a. Haskel version used ZipWith [Signature ((A->A->A) -> [A] -> [A] -> [A]) which is not in scala so I wrote my own version.

(I don’t like the fact that I was not able to pattern match the arguments to map.. to do –> Find a way to pattern match the tuple)

def zipWith[A] (f: (A,A) => A, l1: List[A], l2: List[A]) : List [A] = {

val zipList =>f(x._1,x._2))


———————– Now goes my implementation of the above function —————————-

def pascal(c: Int, r: Int) : Int  {

def pascalH(pr: List[Int], currentRow :Int): List [Int] =


if (r==currentRow) pr else


val l1  = pr :+ 0

val l2 = List(0) ++ pr

val next_list = zipWith((x:Int,y:Int)=> x+y), l1,l2)



val thePascalRow = pascalH(List(1),0)



—– Note that the helper definition works here because scala (as other functional languages) has lexical closure..

I am still new to scala to could not figure out how to use + instead of that lambda in the zipWith call — if you know please leave a comment


Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.