Dynamic function-binding on runtime with Clojure

I started playing with Clojure today and stumbled upon the statement that one could change functions dynamically during runtime. That sounds pretty cool so I wrote a little piece of code using this feature.

(defn ^:dynamic state [x]
   (odd x))

(defn even [x]
  (if (= x 0)
    (println "even")
    (binding [state odd] (parity x))))

(defn odd [x]
  (if (= x 0)
    (println "odd")
    (binding [state even](parity x))))

(defn parity [x]
    (state (dec x)))

It works out fine, but since I am completly new to Clojure I don't know whether this is a) clean functional code (since odd and even seem to have sideeffects?) b) the way changing functions on runtime is supposed to be done

I would appreciate any kind of advice on that! :) -Zakum


Use of dynamic bindings is mostly a question of taste, but there are a few considerations:

Dynamic bindings are pretty much a shortcut for explicitly passing values on the call stack. There are only a few situations where doing that is a totally obvious win; mostly things like passing "global" configuration settings/arguments "through" APIs that don't support them.

An API that relies on dynamic bindings is hard to wrap into something more explicit, while the other way around is much easier (and can usually be done semi-automatically).

Dynamic bindings do not play nice with lazy sequences or anything else that evaluates outside of the current call stack (like other threads).

All in all, I think the "cleaner" functional solution would be to pass state as an argument to parity, but arguments can be made either way.

Need Your Help

Best choices for analyzing custom log files

parsing logging graph

I have written a logger for my projects. I logs to text files and as you may guess there's a time-stamp, namespace, class, method... and finally a log message. Like this:

A good ocaml parser?

parsing ocaml parsec

I'm looking for a good ocaml parsing library that isn't a derivative of flex/bison. Ideally, I'd like a monadic combinator library along the lines of parsec, but I can't find anything.

ASP.NET MVC - posting back only a half of typed view's model?

c# .net asp.net-mvc design

Let's say you're developing your own stackoverflow in ASP.NET MVC :-)

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.