<

Functional programming in scala

Its been a while since i managed to get the time post on my blog, I’ve been really busy with work and home life,

I’ve recently enrolled in an online course. Functional programming in Scala.

I haven’t really touched upon much function programming (except for javascript and a bit of F#). I like it! And i can see its uses! It feels a bit weird entering back into the java world, firing up eclipse etc. I guess i have just become reliant on the friendly features of Visual Studio.

Anyway, here are the answers to the assignment I just submitted for the Functional Programming in Scala!

Pascals Triangle

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

    if (c == 0 || r == c) 1

    else (pascal(c - 1, r - 1) + pascal(c, r - 1));

Parentheses Balancing


def balance(chars: List[Char]): Boolean = {

    def countParenthese(index: Int, list: List[Char]): Boolean = {

      if (index == 0 && list.isEmpty) true

      else if (index < 0 || list.isEmpty) false

      else if (list.head == '(') countParenthese(index + 1, list.tail)

      else if (list.head == ')') countParenthese(index - 1, list.tail)

      else countParenthese(index, list.tail)

    }

    countParenthese(0, chars)

  }

Change Counting

 def countChange(money: Int, coins: List[Int]): Int =

    if (money == 0) 1

    else if (money < 0 || coins.isEmpty) 0

    else countChange(money, coins.tail) + countChange(money - coins.head, coins)

}

Written on October 1, 2012.