Clone
3
Definition
Emin Arslan edited this page 2025-11-03 19:40:17 +00:00

Definition

Operators and functions that add, remove or modify definitions. Other utilities for modifying environments may be included.

set

builtin: (set symbol value)

sets a symbol's bound value. set, being a built-in function, takes a symbol value as its first parameter, meaning that in practice you will need to quote the symbol first. See setq. set always finds the most local definition. For example, the following evaluates to 5:

(def myvar 4)
(defn myfunction (myvar)
  (set 'myvar 5)
  myvar)
(myfunction 4)

And the global myvar will still equal 4 after this. However, set can potentially modify global definitions when the "most local" definition for the given symbol belongs to the global environment. myvar would actually be modified in the following example:

(def myvar 4)
(defn myfunction ()
  (set 'myvar 5)
  myvar)
(myfunction)

This returns 5, and myvar will evaluate to 5 afterwards. Using set for a symbol that doesn't have a binding in the current environment is an error.

setq

macro: (setq symbol value)

Same as set, except setq automatically quotes its first parameter.

(setq x 5) is equivalent to (set 'x 5).

def

builtin: (def sym val)

def creates a new global definition. No quoting is necessary. If the definition already exists in the global environment, it is replaced with the new one - the old one is no longer accessible.

The following evaluates to 5:

(def x 5)
x

defn

macro: (defn sym lambda-list . body)

defn defines a new function in the default global environment.

defn is a shorter way to define functions. It is a macro defined in the standard library. The following code:

(defn my-add (a b)
  (+ a b))

... is equivalent to a combination of def and fn, as seen below:

(def my-add (fn (a b) 
                         (+ a b))) 

The body may be comprised of many forms. In this case, the entire body code is pasted directly into the fn form. As in fn, the entire body of the function will be executed when the declared function is called, and the value of the last expression executed is returned as the value of the function call.

defmacro

macro: (defmacro sym lambda-list . body)

defmacro is similar to defn, with the exception that it defines a new macro in the default global environment.