Allan Jiang
Allan Jiang

Reputation: 11341

LISP global alist variable

I am new to LISP, and here is the question I have with its global variable.

What I am trying to do is to create a "alist" that can store key-value pairs in a structure. Here is my sample code:

(setq *x* '())

(acons 'apple 'fruit *x*)

*x*

(first *x*)

I want my output looks like, after I add the (apple.fruit) pair, x should be ((apple.fruit)), but here is what I got (on loading of the above code):

CL-USER> 
NIL
((APPLE . FRUIT))
NIL  <--- this is still nil?
NIL

Can anyone please help me with this, since I am not sure why I can not add value to the variable x.

Also, I have another question regarding to the alist:
is there a way to look up element in the a list by a key?
for example, for the above list, how can I use the key apple to find its corresponding value fruit?

thank you

Upvotes: 3

Views: 311

Answers (2)

Rainer Joswig
Rainer Joswig

Reputation: 139411

If you want to do Functional Programming, then mutable global variables are definitely not a way to go.

Functional Programming is mostly concerned with computation by calling functions with arguments.

Often solutions are recursive.

Let's say, we have a list of fruits and their prices and we want to have a price sum for each fruit category. Let's try a recursive solution using ACONS.

(defun note-category-price (type price sums)
  (let ((pair (assoc type sums)))
    (if pair
        (progn (incf (cdr pair) price) sums)
      (acons type price sums))))

In above function you can see that the function directly returns the result of calling ACONS. It is not stored.

(defun compute-price-sums (data sums)
  (if (null data)
      sums
    (compute-price-sums (rest (rest data))
                        (note-category-price (first data)
                                             (second data)
                                             sums))))

In above function the extended data structure will be used in the recursive call.

Example:

CL-USER 22 > (compute-price-sums
              '(apple 10 orange 20 banana 10 apple 20
                grape 5 orange 75 apple 30 peach 30
                orange 90 apple 20)
              nil)

((PEACH . 30) (GRAPE . 5) (BANANA . 10) (ORANGE . 185) (APPLE . 80))

Upvotes: 1

Seth Carnegie
Seth Carnegie

Reputation: 75150

The function acons has no side effects, i.e. it doesn't modify *x*.

You have to setq the result to get the result of the acons to stick in *x*:

(setq *x* (acons 'apple 'fruit *x*))

Upvotes: 4

Related Questions