On Mon, May 2, 2011 at 8:23 PM, Nicolas Buduroi <nbudu...@gmail.com> wrote:
> Is there a more functional way of writing it?

If you have imperative code implementing a conceptually-pure function,
the answer to this is always "yes", in at least a trivial sense: you
can write a pure-functional interpreter for the imperative code's
language that that is something like

(defn step [world-state]
  (apply-instruction
    (get-next-instruction world-state)
    world-state))

(defn run [program & arg-list]
  (let [world-state (initial-state-for program arg-list)]
    (extract-output-from
      (first
        (drop-while
          #(not (done-state? %))
          (iterate step world-state))))))

Here, get-next-instruction figures out what instruction to apply next
from a world-state (e.g. it reads a program counter and then an opcode
from an address); apply-instruction applies an instruction to a
world-state to output a new world-state; initial-state-for? takes an
imperative function and an argument list and returns an initial
world-state for executing it in the virtual machine; done-state?
checks if a world-state represents an imperative function that's
finished running rather than still running; and extract-output-from
extracts the return value of that program. If all of those are pure
functions, then so is run.

But I expect most who ask "is there a more functional way of writing
it?" are hoping for something less trivial. :)

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