Welcome back to the second part of the "60 PicoLisp Functions you should know" series.
This time, we will discuss about variables: How to define them, how to work with them, and how to understand their internal representation.
Variables can be set by the command
: (setq A 3) -> 3
The value of a symbol can be checked in the REPL like this:
: A -> 3
We see that
A evaluates to 3. The value of an undefined symbol is
: B -> NIL
Now let's try the same with more complex symbols. Let's set a symbol
Japan. Let's try it the naive way (spoiler: it won't work):
: (setq Country Japan) -> NIL : Country -> NIL
NIL - what happened? As we learned in the previous section, basically everything is a symbol, except for lists and numbers. For the interpreter,
Japan is a symbol and can be evalulated. However,
Japan doesn't have a value, therefore the evaluation returns
Country is set to NIL, too.
Now let's set the
Country to the symbol
Japan itself. For this we need escape the evaluation by using a single quote (
'). Then it will take the symbol
Japan "as such":
: (setq Country 'Japan) -> Japan : Country -> Japan : Japan -> NIL
This is an important difference.
The value of a symbol can be returned by
: (val 'Country) -> Japan : (val 'Japan) -> NIL
We will come back to the
') function again when we will cover anonymous functions (lambda calculus) and other concepts of functional programming.
Any variable can have properties (key-value pairs), which are defined by
put. Now let's fill up our symbol
Japan with some key-value pairs, and give it a value "JP".
: (put 'Japan 'language "Japanese") -> Japanese : (put 'Japan 'continent "Asia") -> Asia : (put 'Japan 'island T) -> T : (setq Japan "JP") -> "JP"
To check the value of a property, we will use
: (get 'Japan 'language) -> "Japanese"
To print the variable with all it's properties, we can use the command
: (show 'Japan) Japan "JP" language "Japanese" island continent "Asia"
In order to fully understand what is happening, let's apply what we learned in the Concept and Data types post. This is the internal representation of symbol
Note that the key "island" does not need a value cell for
T, because its existence already implies that it's
Now we can see the difference between
Japanevaluates to the content of the
VALcell, which is "JP".
'Japanreturns the pointer to the symbol
Japan, i.e. the "symbol" arrow that we see at the top.
Understanding this difference will be very helpful when we discuss more complex operations, for example on lists.
Congratulations, now you know can do basic arithmetics and define variables in PicoLisp. Let's continue with input/output and loops in the next post!