For the example given, I would say it depends on what you are trying to
express.
The function f1 is a function that needs some internal data x to operate
-x might be considered an implementation detail.
The function f2 operates on well known data x -x might be considered
configuration of f2 or a more general concept.
Use both appropriately to write more expressive code -constraining yourself
to only one is like taking some of the colors off your palette.
In addition to the expression differences, there are two closely related
issues that should be considered:
1. There is a difference in the evaluation semantics. In the first
example, the form bound to x is evaluated every time f1 is called. In the
second, the form is invoked just once (at compile time) and then closed
over by f2. That can have very real consequences in real world apps
(performance, side-effects). In simple cases where the form is effectively
constant (as in your example), the compiler may optimize things such that
the costs are equivalent -but I don't think that's a guarantee, especially
on different runtimes (CLR, ClojureScript, etc).
2. There is a scope difference between the two. The second approach allows
you to close over x with multiple functions:
(let [x {:foo 1 :bar 2 :baz 3}]
(defn f3 []
(keys x))
(defn f4 []
(vals x)))
-Chris
On Friday, March 22, 2013 2:59:43 PM UTC-4, jamieorc wrote:
>
> Curious which style is preferred in Clojure and why:
>
> (defn f1 []
> (let [x {:foo 1 :bar 2 :baz 3}]
> (keys x)))
>
> (let [x {:foo 1 :bar 2 :baz 3}]
> (defn f2 []
> (keys x)))
>
> Cheers,
>
> Jamie
>
--
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
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
---
You received this message because you are subscribed to the Google Groups
"Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.