elegance of functional programming

12 Dec 2011

Functional programming allows you to write concise and elegant code. Mainstream languages like Ruby and C# support a lot of functional programming paradigms, and learning them makes you a better programmer. Below is a small example which demonstrates that:

 1 #6 lines of ugly code
 2 i = 0
 3 tasks = list.tasks
 4 while(i < tasks.length - 2)
 5   tasks[i].priority.should >= tasks[i + 1].priority
 6   i += 1
 7 end
 8 
 9 
10 #3 lines of elegant functional code
11 list.tasks.each_cons(2).each do |t1, t2|
12   t1.priority.should >= t2.priority
13 end