Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When you type "hello, world" in Clojure REPL, why does it say 'nil'?

Tags:

clojure

I typed this into Clojure REPL (using the enclojure Netbeans plugin):

user=> "hello, world"
"hello, world"
nil

What's the nil about?

like image 529
uzo Avatar asked Sep 12 '09 20:09

uzo


People also ask

How do I start Clojure REPL?

To start a REPL session in Eclipse, click the Menu option, go to Run As → Clojure Application. This will start a new REPL session in a separate window along with the console output. Conceptually, REPL is similar to Secure Shell (SSH).

What is REPL Clojure?

What is a REPL? A Clojure REPL (standing for Read-Eval-Print Loop) is a programming environment which enables the programmer to interact with a running Clojure program and modify it, by evaluating one code expression at a time.


2 Answers

Every function or macro call returns a value in Clojure, even things like if statements or looping constructs or toplevel function definitions or print statements, which in other languages are "statements". There's no statement/expression dichotomy in Lisps; everything is an expression.

So println and friends print to standard-output as a side-effect and return nil, as do most functions which don't have anything useful to return.

But typing a literal string at the REPL should return the string itself, as in digitalross' post.

user> (println "hello world")
hello world
nil
user> "hello world"
"hello world"
user>

In the first case, the hello world line is what was printed to standard-output by println. nil is the returned value of println. In the second case, "hello world" is the returned value of "hello world" since a string evaluates to itself. Nothing is printed to standard-output in this case.

(SLIME and some other REPL interfaces will helpfully color standard-output (the hello world line above) differently from the returned value of what you typed at the REPL (nil above), since it might be confusing otherwise.)

This is what you should see at a REPL. What you posted must be an artifact of Enclojure.

like image 117
Brian Carper Avatar answered Oct 28 '22 18:10

Brian Carper


Can't reproduce...

It doesn't do that for me on Clojure 1.0.0-

$ java -cp clo*.jar clojure.lang.Repl
Clojure 1.0.0-
user=> "hello, world"
"hello, world"
user=> 
like image 21
DigitalRoss Avatar answered Oct 28 '22 19:10

DigitalRoss