Skip to content
Tutorials Center
My learning

Topics

Lesson 3 of 38 ยท Getting Started

Your First Lisp Programs

Write Hello World, print with format, define functions in a file, load and compile code, and build a small temperature converter in Common Lisp step by step.

Time to write real programs. In this lesson you will print text, do arithmetic, define functions, put code in a file and load it, and build a small program that converts temperatures. The Lisp listings are read-only, because the compiler does not run on this site; the TryIt blocks run the same ideas on a labelled JavaScript Mini-Lisp stand-in (a toy interpreter, not SBCL).

Hello, world

The classic first program in Common Lisp:

LISP
(format t "Hello, world!~%")

format is the workhorse of output. Its first argument is the destination: t means standard output. The second argument is a control string. Inside it, ~% prints a newline, and ~a inserts the next argument in human-readable form.

LISP
(format t "My name is ~a and I am ~a years old.~%" "Ada" 36)
;; prints: My name is Ada and I am 36 years old.

Other printing functions you will meet:

Function What it does
(print x) Newline, then x as Lisp would read it, then a space
(prin1 x) x readably (strings keep their quotes), no newline
(princ x) x for humans (strings without quotes), no newline
(terpri) Prints a newline
(format nil ...) Does not print: returns the formatted string
LISP
(prin1 "hi")   ; prints "hi" with the quotes
(princ "hi")   ; prints hi
(format nil "~a plus ~a is ~a" 2 3 (+ 2 3))   ; => "2 plus 3 is 5"

Always remember: in the REPL the value of a form is printed too. (format t ...) prints text and returns NIL, so you will see both the text and NIL.

Arithmetic with prefix notation

Lisp puts the operator first. This is called prefix notation.

LISP
(+ 1 2)            ; => 3
(* 2 3 4)          ; => 24 (operators take any number of arguments)
(- 10 3)           ; => 7
(/ 10 4)           ; => 5/2   (an exact ratio, not 2.5!)
(/ 10.0 4)         ; => 2.5
(+ 1 (* 2 3))      ; => 7     nested: inner form first

Because every call is fully parenthesized, there is no precedence to remember: (+ 1 (* 2 3)) and (* (+ 1 2) 3) say exactly what they mean.

Here is the same arithmetic on the Mini-Lisp stand-in. Mini-Lisp uses JavaScript numbers, so it prints 2.5 where real Common Lisp would print the exact ratio 5/2.

JS Mini-Lisp: prefix arithmetic

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Defining a function

defun defines a named function: its name, a parameter list, and a body. The last form in the body is the return value.

LISP
(defun square (x)
  (* x x))

(square 5)    ; => 25
(square 1.5)  ; => 2.25

A function can include a documentation string as its first body form:

LISP
(defun area-of-circle (radius)
  "Return the area of a circle with the given RADIUS."
  (* pi radius radius))

(documentation 'area-of-circle 'function)
;; => "Return the area of a circle with the given RADIUS."

pi is a built-in constant. In SBCL it is a double-float, so (area-of-circle 2) prints 12.566370614359172d0.

Local variables with let

let introduces local variables, valid only inside its body:

LISP
(defun hypotenuse (a b)
  (let ((a2 (* a a))
        (b2 (* b b)))
    (sqrt (+ a2 b2))))

(hypotenuse 3 4)   ; => 5.0

The shape ((name value) (name value)) is the list of bindings. We look at scope in depth in Symbols, Variables and Scope.

JS Mini-Lisp: functions and let

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Putting code in a file

Create a file called temperature.lisp:

LISP
;;; temperature.lisp -- convert between Celsius and Fahrenheit

(defun celsius-to-fahrenheit (c)
  "Convert C degrees Celsius to Fahrenheit."
  (+ 32 (* c 9/5)))

(defun fahrenheit-to-celsius (f)
  "Convert F degrees Fahrenheit to Celsius."
  (* (- f 32) 5/9))

(format t "100 C is ~a F~%" (celsius-to-fahrenheit 100))
(format t "212 F is ~a C~%" (fahrenheit-to-celsius 212))

Run it from the shell:

Terminal
sbcl --script temperature.lisp

Expected output (real SBCL):

TEXT
100 C is 212 F
212 F is 100 C

Comments start with ;. By convention you use ; for a comment at the end of a line, ;; for a comment on its own line inside code, and ;;; for a heading-level comment at the top of a file or section.

Notice 9/5 and 5/9: these are ratios, exact fractions. Using them keeps conversions exact for integers. If you want decimals, write 9/5 as 1.8.

Loading and compiling

From the REPL, load the file to define everything in your session:

LISP
(load "temperature.lisp")
(celsius-to-fahrenheit 37)   ; => 493/5

(celsius-to-fahrenheit 37) returns 493/5 (that is 98.6 as a fraction). To see a decimal, use a float: (celsius-to-fahrenheit 37.0) gives 98.6.

compile-file turns the source into a .fasl (fast-load) file, and load can read either:

LISP
(compile-file "temperature.lisp")   ; writes temperature.fasl
(load "temperature")                ; loads the newest of .fasl or .lisp

SBCL compiles every function you type at the REPL anyway, so compile-file mostly matters for distributing code or checking for warnings.

Reading what the compiler tells you

If you misspell a function, the compiler prints a style warning at the end of the file and the program fails at run time:

LISP
(defun oops (x) (squar x))   ; typo
TEXT
; caught STYLE-WARNING:
;   undefined function: COMMON-LISP-USER::SQUAR

At run time, calling (oops 3) signals an undefined-function error. Read the warning and fix the name.

A tiny interactive program

Reading user input uses read-line:

LISP
(defun ask-name ()
  (format t "What is your name? ")
  (finish-output)                       ; make sure the prompt appears
  (let ((name (read-line)))
    (format t "Nice to meet you, ~a!~%" name)))

finish-output flushes the output buffer so the question shows before the program waits.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (format nil "~a-~a" 1 2) do?

    With nil as the destination, format builds and returns a string instead of printing.
  2. 2. What does (/ 10 4) return in Common Lisp?

    Integer division of non-multiples yields an exact ratio. Use (/ 10.0 4) for 2.5.
  3. 3. Which command runs a Lisp file non-interactively?

    --script runs the file and exits.
  4. 4. What is the value returned by a function defined with defun?

    Common Lisp functions return the value of their last body form (there is no required return keyword).

Summary

  • (format t "...~%") prints; (format nil ...) returns a string.
  • Operators come first: (+ 1 2); nesting replaces precedence rules.
  • defun defines functions; the last form is the return value; add a docstring.
  • let makes local variables.
  • Files hold code; run with sbcl --script file.lisp, or (load "file.lisp") in the REPL.
  • / of integers yields exact ratios.

Next: REPL Workflow and the Debugger