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!
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With