Reading — step 1 of 5
Learn
~1 min readFunctions and Lists
Define a named function with defun:
(defun square (n)
(* n n))
(square 5) ; 25
The parameter list is a vector of names. The body is one or more expressions; the last is the return value.
Optional parameters with &optional:
(defun greet (name &optional (greeting "Hello"))
(format nil "~a, ~a!" greeting name))
(greet "Ada") ; "Hello, Ada!"
(greet "Ada" "Hi") ; "Hi, Ada!"
format nil instead of t returns the string instead of printing.
Anonymous functions with lambda:
(lambda (x) (* x 2))
((lambda (x) (* x 2)) 5) ; 10 — call inline
Functions are first-class — pass them with #':
(mapcar #'square '(1 2 3 4)) ; (1 4 9 16)
The #' (sharp-quote) extracts the function value from the symbol.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…