Imperative into functional?

0 views
Skip to first unread message

Michael Jaaka

unread,
Nov 8, 2009, 11:41:00 AM11/8/09
to Clojure
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)

Mark Engelberg

unread,
Nov 8, 2009, 1:03:47 PM11/8/09
to clo...@googlegroups.com

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...)

Reply all
Reply to author
Forward
0 new messages