Is there a coding convention for a better place "coll" and "n" for Clojure?

While I'm writing clojure code, I'm confused when to follow the format (func coll n) and (func n coll) .
In Clojure / core, (take n coll) used, and (nth coll n) also the correct code. In addition, there are (reduce func n coll) , (get coll n) and (drop n coll) .
Is there a rule / convention for the right place of type of argument when defining these intricate functions? Or should I just type doc every time without meaning?

+5
source share
2 answers

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

 (take n coll) (drop n coll) 

In both cases, the semantically most important is how many elements you accept / discard.

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

(coll n)

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

In the end, I think the most intuitive meaning for the caller is probably the best and will make your code the most readable / supported by future users of your code.

There are other considerations. For example, options for using variable arguments (for example, using & more ), where you will need the necessary arguments to prevent ambiguity in the first place. However, I would still consider readability, since the functions of variable arguments can have their own readability problems. See this wonderful post from Stuart Sierra that talks about it.

+5
source

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

The format (func coll n) used to select items from the collection, using nth for the seq or get collection (which can be omitted) from the associative collection.

+3
source

Source: https://habr.com/ru/post/1239657/


All Articles