Association Lists in LISP
Association Lists in Lisp are used for mapping values to respective key elements. They are also known as a-list. The car of the pair represents the key element whereas cdr represents the associated value.
Creating a list:
1. Using list and cons: In this method, we make use of lists and cons for creating our lists.
Lisp
; Creating a list with name of the student ; as the key and marks as the value using list and ; cons method (defparameter * marks * ( list (cons 'kishan 96) (cons ' saksham 92 ))) |
2. Using pairlis: Another method for list creation is using Pairlis which eliminates the use of list and cons totally.
Lisp
;Creating list using pairlis (pairlis '(kishan saksham) ' ( 96 98 )) |
3. Using acons: A single pair can be added to a list using the acons function.
Example 1:
Lisp
;Using acons to add pair ( defvar * marks * (pairlis '(Kishan Saksham) ' ( 96 98 ))) ( defvar * new - marks * (acons 'shubh 91 * marks * )) (write(assoc 'shubh * new - marks * )) |
Output:
Retrieval Function in Association List:
For the retrieval of the data from the list, we use a function assoc which is used to return the value corresponding to the key element. The parameters it uses are key, association list, and some testing keywords such as (key, test,test-not). Note that the testing keywords we use are totally optional.
Example 2:
Lisp
; Lisp code for assoc (defparameter * marks * ( list (cons 'kishan 96) (cons ' saksham 92 ))) (write(assoc 'kishan * marks * )) |
Output:
Note: If the item is not in the list then the assoc function will be returning nil.
Example 3:
Lisp
; Lisp assoc returning nil in ; case when value is not present (defparameter * marks * ( list (cons 'kishan 96) (cons ' saksham 92 ))) (write(assoc 'sakshi * marks * )) |
Output:
Updating the values in a list for some key elements:
In Lisp, we make use of the macro setf whenever we want to perform updation. Similarly, we use setf in association lists and also its in-built functionalities for updation of values. Note that setf is used along with cdr since we are updating the value part and not accessing the key.
Example 4:
Lisp
; Updating the value associated with key "kishan" (defparameter * marks * ( list (cons 'kishan 96) (cons ' saksham 92 ))) ( setf ( cdr (assoc 'kishan * marks * ) ) 99 ) (write(assoc 'kishan * marks * )) |
Output:
The rassoc function:
In association lists, we can also retrieve the key based on value as a bi-directional map. This we can do with the help of rassoc function which is a reverse assoc function.
Example 5:
Lisp
; Using the rassoc function (defparameter * marks * ( list (cons 'kishan 99) (cons ' saksham 92 ))) (write(rassoc ' 99 * marks * )) |
Output:
Contact Us