0

Bearing in mind, “Programs are meant to be read by humans and only incidentally for computers to execute.” I want to better understand how I can best express the intent of the argument(s) passed to a function. For example, I have a very simple function:

user=> (defn add-vecs 
         "Add multiple vectors of numbers together"
         [& vecs] 
         (when (seq vecs) 
           (apply mapv + vecs)))

Which in action will do the following:

user=> (add-vecs [1 2 3] [1 2 3] [1 2 3])
[3 6 9]

I don’t like relying on the doc-string to tell the reader of the code the requirements of the argument because comments often lie, developers don’t always read them and code changes but comments rarely do.

I could rename vecs something like "vecs-of-numbers" but that feels clumsy.

I appreciate Clojure is both dynamic and strongly typed and this question is clearly in the area of typing. So in general, and if possible some examples for this case, what would make the function argument(s) more readable?

1 Answer 1

1

When what you want is a type, use a type. There are several approaches to typing available. I'll use prismatic.schema in this case because it's fairly unimposing:

(require '[schema [core :as schema]]])

(schema/defn add-vecs [& vecs :- [Schema/Number]]
   ... code here ... )

or you can add a pre-condition to check it as runtime:

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you… I’ve come across core.typed but not prismatic.schema. What benefit does it have over core.typed? It looks like your reply on a pre-condition has been cut short. What were you going to say?
I don't think one is better than the other in general. At work we use prismatic.schema because it's easy to include it in the small fraction of the code where it's required and it can produce nice error messages at runtime. for instance it validates API requests and responses. core.typed is more capable perhaps of covering an entire system. I'll try to restore the pre-condition example this afternoon.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.