2 Diving In

2.4 Variables

2.4.1 Variables in the REPL

Variables in LFE don't have the same syntactical limitations that vanilla Erlang has. Let's take a look at some examples in the REPL:

> (set &$% "Mostly Harmless")
"Mostly Harmless"
> &$%
"Mostly Harmless"

Your variable does not have to start with a capital letter and not only can it contain special characters, it can entirely consist of them! We don't recommend this, however ;-)

Furthermore, LFE also does not share with Erlang the characteristic of not being able to change a variable once you've set it's value. In the REPL you can do this without issue:

> (set phrase "Don't Panic")
"Don't Panic"
> phrase
"Don't Panic"
> (set phrase "Mostly Harmless")
"Mostly Harmless"
> phrase
"Mostly Harmless"
>

In previous sections we've set variables and worked with those variables in the REPL (saving us some typing), so this should all seem a bit familiar.

As such, this should be fairly intuitive clear at this point:

> (set the-answer 42)
42
> (* the-answer 2)
84
> (* the-answer the-answer)
1764
> (* the-answer the-answer the-answer)
74088
>

Unlike Erlang, the LFE REPL doesn't have the b() and f() functions ("show bound variables" and "flush bound variables" respectively).

2.4.2 Variables in LFE Modules

Unlike Lisp, LFE doesn't support global variables, so (unless you create some dirty hacks!) you won't be doing things like this in your modules:

(defvar *sneaky-global-data* ...)
(defparameter *side-effect-special* ...)
(defconstant +my-constant+ ...)

(Not to mention that LFE doesn't even define defvar, defparameter, or defconstant.)

As such, you shouldn't run into variables that are defined at the module-level, only inside actual functions.

2.4.2 Variables in Functions

There are all sorts of ways one might set a variable in an LFE function. The snippets below illustrate some of these, though for demonstration purposes, they are executed in the REPL.

> (let ((x 2)
        (y 3))
    (list x y (* x y)))
(2 3 6)
>

Above we set two variables, and then withing the scope of the let with display some values, one of which is computed from the variables.

> (let* ((x 2)
         (y 3)
         (z (* x y)))
    (list x y z))
(2 3 6)
>

In this example, we make use of let*'s ability to use defined variables in subsequent variables assignments. Tying this with regular let will result in an error.

> (let (((tuple name place age) #("Ford Prefect" "Betelgeuse Seven" 234)))
    (list name place age))
("Ford Prefect" "Betelgeuse Seven" 234)
>

Here is an example of multiple-binding in LFE. We haven't covered patterns yet, but we will -- and this example is making use of patterns to assign data from the given record to the variables in the tuple.

Patterns may be used in several different LFE forms, each of which may do some varaible binding.