Programming Languages

Lisp Basics

Jim Posen - ECE/CS 2014

Data Types

  • Atoms
  • Lists

Atoms I

Numbers, booleans, symbols, characters, strings

1
2.0
#t
abc
#\a
"hello"

Lists

A series of elements surrounded by parenthesis

(a b c "easy as" 1 2 3)

Lists may contain any S-expression

S-expressions

An S-expression is just an atom or a list

Everything in LISP is an S-expression

(i s n t (t h i s) (c () () l?))
Yes, even code is made of S-expressions
(define (factorial n)
  (if (zero? n)
    1
    (* n (factorial (- n 1)))))

Lists Revisited

  • Lisp uses linked lists made of conses
  • A list is either null or a cons

Cons

A cons is just a pair of values

Simple cons

(setf x (cons 'b null))

Two element list

(setf x (cons 'a (cons 'b null)))

Nested lists

(setf x '(a (r t) b))

Program Structure and Evaluation

Evaluation

  • Lisp programs are made of S-expressions
  • eval interprets and evaluates an S-expression
  • The top level is called the Read Eval Print Loop or REPL
(eval '(+ 1 2 3))  ;; 6
(eval '(a b c))    ;; Crash -- a is undefined

Function application

  • Lisp uses prefix notation
  • The first element of an evaluated list is the function
  • foo(1, 2, 3) => (foo 1 2 3)
  • 1 + 2 + 3 => (+ 1 2 3)
(+ 1 2 3)           ;; 6
(- 1 2 3)           ;; -4
(* (+ 1 2) (- 5 3)) ;; 6

Argument evaluation

Function arguments are evaluted in order

quote

How to prevent evalutation of an expression?

(setf x (a b c))  ;; CRASH -- a is undefined
(setf x (quote (a b c)))  ;; Aha, much better
  • quote does not evaluate its argument
  • quote is a primitive

Single quotes are a shorthand for quote

(setf x '(a b c))  ;; Even better yet

Exercises with numbers

Primitive List Operations

  • car
  • cdr
  • cons

car

  • Returns the first element of the cons
(car '(a b c))          ;; 'a
(car '((a b c) d e f))  ;; '(a b c)
(car '())               ;; Oh noes -- CRASH

cdr

  • Returns the second element of the cons
  • Often the remainder of the list without the first element
(cdr '(a b c))          ;; '(b c)
(cdr '((a b c) d e f))  ;; '(d e f)
(cdr '((a b c)))        ;; '()
(cdr '())               ;; Oh noes -- CRASH

cons

  • Creates a new cons
(cons 'a '())                ;; '(a)
(cons 'a '(b))               ;; '(a b)
(cons '(a b) (cons 'c '()))  ;; '((a b) c)
(cons 'a 'b)                 ;; '(a . b)