Friday, November 9, 2012

Think Functionally - Writing program the functional way

After taking the "Functional Programming Principles in Scala" course on Coursera.org, my understanding and appreciation for "thinking" functionally grew a lot. One of the big benefits the course have on me is fixing my misconception on recursion. I had disliked writing recursive functions thinking it was very susceptible to stack overflow. Although this is true, the course explanation on tail call help correct my misunderstanding.

I was just browsing the IT forum on discuss.com.hk and came across a post on a university question on about writing a program to give change to for a vending machine (note it is in Chinese). Don't worry about he forum. Although there are a definitely a few good developers in there, the questions and discussion are generally of pretty low quality. I just browse occasionally hoping it will help me getting to know the IT industry in Hong Kong a little better.

I recall doing a similar problem in university for either an assignment or exam question, and I recall doing it the "Imperative way" with loops and states. It was an awful experience.
Now arm with thinking functionally, I took another crack at it and seems much easier.