Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there coding convention for better place of 'coll' and 'n' for Clojure?

While I write clojure code, I'm confused about when to follow (func coll n) format and (func n coll) format.
In Clojure/core, (take n coll) is used while (nth coll n)is also right code. Also, there are (reduce func n coll), (get coll n), and (drop n coll).
Is there any rule/convention for right place of argument type while defining these confusing functions? Or should I just type doc everytime without sense?

like image 563
burrownn Avatar asked Jan 02 '16 07:01

burrownn


2 Answers

I think it depends. Perhaps the core library actually best exemplifies this. If you look at the examples you cited:

(take n coll) 
(drop n coll)

In both these cases, semantically, the most important thing is how many elements you are taking/dropping.

In the case of something like (get coll n), there's a left-to-right semantic of first having a collection before having an index with which to fetch. I think nth is the same in this regard. Note, there are other ways to get indexed elements from a collection - for example you can also just do this:

(coll n)

This works because clojure data-structures like vector, hash-map and set can all act as functions. IMO, this is a more confusing way to accomplish the same thing as it is often harder to read and does not show intent nearly as clearly as (get coll n).

In the end I think what makes the most intuitive sense to the caller is probably best and will make your code the most readable/maintainable by future users of your code.

There are other considerations. For example, variable-arity use cases (e.g. using & more), where you will need the required arguments to come first to prevent ambiguity. I would still consider readability first however, as variable argument functions can come with their own readability issues. See this great post from Stuart Sierra which talks about this.

like image 107
leeor Avatar answered Nov 10 '22 17:11

leeor


The (func ... coll) format is used for the sequence library: map, filter, reduce, &c. The intervening arguments are more often functions than numbers.

The (func coll n) format is used to select elements from the collection, using nth for a seqable collection or get (which may be omitted) from an associative collection.

like image 24
Thumbnail Avatar answered Nov 10 '22 17:11

Thumbnail