ffriend
ffriend

Reputation: 28472

What is convention for local vars that has same meaning as function argument?

What is convention for local vars that has same meaning as function argument?

If I need local variable that has as its initial state value of function argument (and thus has the same meaning), how should I call it?

As artificial example (that, however, demonstrates quite popular construction in Clojure):

(defn sum [coll]
  (loop [local-coll coll, result 0]
    (if (empty? local-coll)
       result
       (recur (rest local-coll) (+ (first local-coll) result)))))

Here local-coll is initialized to the value of coll initially, and it also holds this meaning during looping. local-coll is definitely not a good name for it, but what is?

In Haskell it is a good style to put quote (') to the end of variable/function name, e.g. var'. In Common Lisp sometimes I saw names ending with asterisk (*). Clojure has same notation for function that duplicate another function meaning but have a bit different semantics (e.g. list*). But this notation is also frequently used in docstrings to indicate that there may be several items of this type (e.g. (methodname [args*] body)* or (try expr* catch-clause* finally-clause?)) and thus can confuse when used for local var names. Java interop also provides things like defn-, that is names ending with hyphen (-) to indicate private methods in generated classes. So it makes some sense to use hyphen for local (private for a function) variables too (though it seems a bit weird for me).

So, what the way should I go when naming my local variables with the same meaning as function argument?

Upvotes: 2

Views: 209

Answers (1)

liwp
liwp

Reputation: 6926

I think it's fine to shadow the argument name when you don't need the original argument any more:

(defn sum [coll]
  (loop [coll coll, result 0]
    (if (empty? coll)
       result
       (recur (rest coll) (+ (first coll) result)))))

Other variations that I've seen are:

(loop [c colls] ...)
(loop [coll initial-coll] ...)
(loop [foo foo-coll] ...)
(loop [s specs] ...)

Upvotes: 8

Related Questions