Functions in Lisp

Functions are central in Lisp. We’ll learn about functions with a few different examples.

;; Here's a function that takes two numbers and returns their sum
(defun plus (a b)
  (+ a b))

;; In Lisp, we don't need to specify types, and multiple parameters
;; are naturally supported without any special syntax
(defun plus-plus (a b c)
  (+ a b c))

;; The main function in Lisp is typically not explicitly defined,
;; but we can create one for demonstration purposes
(defun main ()
  ;; Call a function just as you'd expect, with (name args)
  (let ((res (plus 1 2)))
    (format t "1+2 = ~a~%" res))

  (let ((res (plus-plus 1 2 3)))
    (format t "1+2+3 = ~a~%" res)))

;; To run the program, we can call the main function
(main)

To run this Lisp program, you would typically save it to a file (e.g., functions.lisp) and then load it into a Lisp interpreter or compile and run it, depending on your Lisp implementation.

For example, using SBCL (Steel Bank Common Lisp):

$ sbcl --script functions.lisp
1+2 = 3
1+2+3 = 6

In Lisp, functions are first-class citizens, meaning they can be passed as arguments, returned from other functions, and assigned to variables. This makes Lisp particularly powerful for functional programming paradigms.

Lisp doesn’t require explicit type declarations for function parameters or return values, as it’s dynamically typed. However, some Lisp dialects and implementations support optional type declarations for optimization or documentation purposes.

The defun special form is used to define functions in Lisp. The general syntax is (defun function-name (parameters) body).

Lisp uses prefix notation, where the function name comes before its arguments, enclosed in parentheses. This is different from many other languages but allows for powerful macro systems and code-as-data paradigms that Lisp is known for.

There are several other features to Lisp functions, including multiple return values, optional parameters, and keyword arguments, which we might explore in subsequent examples.