On Sun, Nov 8, 2009 at 8:41 AM, Michael Jaaka
<michael.ja...@googlemail.com> wrote:
> Can any imperative code be transformed to functional equivalent?
> (Give an answer in terms of the same way I can answer on recursion and
> loops)

Short answer: Yes.
Long answer:  Yes, but sometimes the transformation can get rather unwieldy.

Most of the time, such transformations are easy.  For example, when
writing the clojure-contrib combinatorics library, I was transforming
highly imperative register-based algorithms from Knuth's books into
loop/recur using Clojure's functional vectors.  It's just as
inscrutable to read as the original, but it was fairly easy to
transform.

The basic technique is to, rather than change something in place and
"returning void", you return the changed version from a function.

The problem is that sometimes, there are many different pieces of many
different states that need to be updated, and you end up passing more
and more things around in a functional way until eventually you are
threading some monolithic "world state" through all your functions,
basically simulating the imperative process. This is where monads can
come in handy, to help hide the threading of the monolithic state.
But at this point, it's not clear whether you're really any better off
than doing it imperatively to begin with.  That's why it's good that
Clojure has a suite of mechanisms for dealing with state (agents,
refs, vars, atoms...)

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to