Land of Lisp - Ch1 & Ch2
TL;DR
Loading Source Files
> (load "my_lisp_file.lisp")
clisp "my_lisp_file.lisp"
sbcl --load "my_lisp_file.lisp"
Global Vars
> (defvar +golden_ratio+ 1.616) ; immutable
> (defparameter *foo* "foo") ; mutable
Functions
(defun my_super_duper_function (...args...)
... body of function ...)
Local Variables
(let ((var1 val1)
(var2 val2))
...body...)
(let* ((var1 val1)
(var2 var2))
...body...)
Local Functions
; flet doesn't allow for local functions to call each other - no recursion
(flet ((function_name (arguments)
...function body...))
... body ...)
; labels allows local functions to call each other (can recurse)
(labels ((function_name (arguments)
... function body ...))
... body ...)
Chapter 1
Loading source files...
> (load "my_lisp_file.lisp")
Or...
clisp "my_lisp_file.lisp"
sbcl --load "my_lisp_file.lisp"
Chapter 2
Global Variables
Defining a constant (convention is to surround name with + symbols)
(defvar +golden_ratio+ 1.6180339)
Define a mutable global variable
(defparameter *myval* 1)
"Earmuffs" The asterixes surrounding a variable are referred to as ear muffs. It's a Lisp convention that these are used to identify global variables. The asterixes are part of the name.
defvar and defparameter
defvar
will only set a value once. If defvar
is used to change a variable's value again, the value will not change. The value can be changed with calls to other functions (such as defparameter
). e.g.
[1]> (defvar +hello+ "Hello") ; define the value
+HELLO+
[2]> +hello+
"Hello"
[3]> (defvar +hello+ "Hello World") ; defvar won't change value
+HELLO+
[4]> +hello+
"Hello"
[5]> (defparameter +hello+ "Hello World") ; defparameter WILL change the value
+HELLO+
[6]> +hello+
"Hello World"
see also: setf
and setq
Defining a Function
(defun func_name (arguments)
... body ... )
Defining Local Variables
(let
(variable declarations)
..body... )
Defining Local Functions
There are two ways to define a local function in Lisp flet
and labels
.
flet
functions can only be called by the body
labels
allows local functions to call themselves and other local functions.
It's a convention to default to the use to flet
unless labels
is required. This way if you see labels
in code you can expect functions to be calling each other and that recursion is likely.
flet
(flet
((function_name_1 (arguments) ... function 1 body...)
(function_name_2 (arguments) ... function 2 body...))
... body ... )
e.g.
(flet
((f (n) (+ n 10))
(g (n) (- n 3)))
(g (f 5)) )
labels
(labels
((function_name (arguments)
... function body...))
... body ... )
e.g.
(labels
((a (n) (+ n 5))
(b (n) (+ (a n) 6)))
(b 10))