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?
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.