Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why there is a "nil" at the end of output in clojure

Tags:

clojure

I am wondering why there is a "nil" at the end of output in clojure. Here is my code:

(defn foo [x &argu]
    (print x &argu))

And the other question is what does "&argu" mean here? An variadic argument or something? Thank you so much!

like image 204
Xiufen Xu Avatar asked Dec 25 '22 09:12

Xiufen Xu


1 Answers

The REPL (or whatever execution environment you are using) lets you know the output of the evaluation of the code. As you have written it your function does not return anything. In such cases nil is returned by convention. nil is Clojure's marker for nothing/null. All your code is doing is printing - which is a 'side effect'.

It is important to note that nil is a proper value in Clojure. This is in contrast to some languages that won't even let you compare the undefined/unknown value with another that is a proper value - doing so will generate an exception.

Normally there's a space, so [x & argu]. It matters - so please put the space in your code and try again. This means that the function takes one or more parameters. You are quite correct in saying that it is 'varadic'.

Most languages have the concepts of 'nil' and 'varadic arguments'. Because Clojure is a functional language the whole thinking around 'only returning' from functions becomes quite important. Prioritising not having side effects in your code makes it easier to reason about.

This is your function changed just a little:

(defn foo [x & argu]
  (println x argu))

And this is example usage in the REPL:

=> (foo 3 "Hello" "how" "are" "you?")
3 (Hello how are you?)
nil

See how inside the function argu has become a list.

like image 127
Chris Murphy Avatar answered Jan 06 '23 16:01

Chris Murphy