Local variables are good in these situations

1) You want to accumulate some changes eg:
// sum odds
int x = 0;
for (int i=0; i<100; i++) {
   if ( i%2==1 ) x+=i; }

;It is relatively easy to rearrange these sort of things into a form
that requires no variables
user=> (reduce #(+ %1 (if (= 1 (rem %2 2)) %2 0)) (range 100))
2500

2) You need to save a result and use it multiple times:
Can work around this with let:
(let [g (rand 0.8)]
  (Color3f.  (+ 0.2 g) (+ 0.2 g) (+ 0.2 g)))

3) Java interop:
I find using java libraries often forces you into a situation where
you want to use a local variable.
You can always get around it by using nested lets though it makes the
code ugly. However keep in mind doto.
The great thing about doto is that it returns the object after
applying several calls, so it allows you to avoid nesting lets in a
lot of situations:
(doto (MainFrame. (doto (Applet.)
        (setLayout (BorderLayout.))
        (add "Center" (.getCanvas *universe*)))
    1024 512)
  (setTitle "2D Plotting in Clojure"))

4) Mutating permanent state variables
Use refs with some simple wrappers to reduce the syntax requirements


I find that if I follow those four principles I can usually figure out
how to translate from variables to non-variables.

I don't fully understand why local variables are such a Bad Thing...
or if it is just a style enforcement... but I remember reading
somewhere that Clojure doesn't use the stack hence no local variables.

--~--~---------~--~----~------------~-------~--~----~
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
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/clojure?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to