On Fri, Jun 07, 2013 at 09:44:36PM -0700, Guy Sotomayor wrote:
On Jun 7, 2013, at 8:59 PM, ben <bfranchuk at
jetnet.ab.ca> wrote:
I have no problems with iteration or subroutines,
so why do we need
recursion?
Recursion is a tool, just like iteration. In cases where it's
useful the code
is clearer/cleaner than if it was written with say iteration.
There is a certain amount of confusion forming in this thread. It is idiomatic
in functional programming to use recursion for things that would normally be
done with iteration in imperative languages.
This is because "variables" aren't, and you can't assign new values to
them.
That means no loop counters, for example. So one "cheats" by creating a little
helper function into which the value you want to change is passed into it, and
which calls itself where necessary. The compiler's optimiser then uses
tail-call optimisation to turn it back into a loop again!
There are two reasons for the immutability of variables. The first reason is
because ivory-tower computer scientists are really crusty old mathematicians at
heart and that's what the theory dictates. I think these people should get out
more.
The second reason is one I am much more interested in. Because variables are
immutable, this means data structures can be shared between threads without
having to faff around with atomic updates and locking. This takes away some
incredibly hard-to-debug problems with synchronisation and data corruption.
In real-world code, you need a hybrid approach, which is why I've a certain
fondness for Scala which allows me to use functional most of the time, but also
drop in imperative code in hot spots that need a bit more performance.