What follows is an excerpt from a REPL session with Common Lisp in which a "Hello, World!" function is defined and executed. See the remarks at the bottom of this page for a more thorough description of a REPL.
CL-USER> (defun hello ()
(format t "Hello, World!~%"))
HELLO
CL-USER> (hello)
Hello, World!
NIL
CL-USER>
This defines the "function" of zero arguments named hello
, which will write the string "Hello, World!"
followed by a newline to standard output, and return NIL
.
To define a function we write
(defun name (parameters...)
code...)
In this case the function is called hello
, takes no parameters and the code it runs is to do one function call. The returned value from a lisp function is the last bit of code in the function to run so hello
returns whatever (format t "Hello, World!~%")
returns.
In lisp to call a function one writes (function-name arguments...)
where function-name
is the name of the function and arguments...
is the (space-separated) list of arguments to the call. There are some special cases which look like function calls but are not, for example, in the above code there is no defun
function that gets called, it gets treated specially and defines a function instead.
At the second prompt of the REPL, after we have defined the hello
function, we call it with no parameters by writing (hello)
. This in turn will call the format
function with the parameters t
and "Hello, World!~%"
. The format
function produces formatted output based on the arguments which it is given (a bit like an advanced version of printf
in C). The first argument tells it where to output to, with t
meaning standard-output. The second argument tells it what to print (and how to interpret any extra parameters). The directive (special code in the second argument) ~%
tells format to print a newline (i.e. on UNIX it might write \n
and on windows \r\n
). Format usually returns NIL
(a bit like NULL
in other languages).
After the second prompt we see that Hello, World
has been printed and on the next line that the returned value was NIL
.