Lists in LISP
Lists in common LISP is simply a single Linked list. In LISP, Lists are designed as a chain of records. While talking about record structures in LISP, the concept of Cons is vital. Cons in LISP is a record structure with 2 primary components. A cons function takes in 2 arguments and returns a new cons cell with car and dir.
- car: It is used to access the first value in a cons function.
- cdr: It is used to access the second value in the cons function.
Note: If the second value is not nil or is just another cons cell, then the values are printed as a dotted pair enclosed by parentheses.
Example:
Lisp
; cons with 2 string object reference(write (cons 'Geeksforgeeks 'Is_Best))(terpri); cons with 1 nil value as argument(write (cons 999 nil))(terpri);cons with another cons as argument(write (cons 'A (cons 'B nil)))(terpri);cons with otyhen nested cons as argument(write (cons 'A (cons 'B (cons 'C nil)))) |
Output:
(GEEKSFORGEEKS . IS_BEST) (999) (A B) (A B C)
Lists in LISP:
The list function in LISP can be used to create a list in LISP.
Syntax:
write( list value1 value 2 ...)
Note: The list function can take any no. of arguments.
Example:
Lisp
(write (list 1 2))(terpri)(write (list 'g 'e 'e'k's))(terpri)(write (list 'Geeksforgeeks' nil))(terpri);list with a cons as an argument(write (list 3 4 'geeks (car '(G . F)) (* 99 +78)))(terpri); list with another list as an argument(write (list (list 'Geeksforgeeks 'is) (list 'the 'best 'resource 'for 'DSA))) |
Output:
(1 2) (G E E K S) (GEEKSFORGEEKS NIL) (3 4 GEEKS G 7722) ((GEEKSFORGEEKS IS) (THE BEST RESOURCE FOR DSA))
Accessing Elements of a LIST:
The combination of car and cdr functions in common LISP can be used to extract elements from a list. The combination of carr and cdr can be abbreviated as cadadr/caar/cadr and so on.
Example:
Lisp
; here we will extract the string Best(write (cadadr '(Geeksforgeeks (is best) (for Data Structures))))(terpri); here we will extract the string Geeks(write (caar (list (list 'Geeks 'for) 'geeks))) (terpri); here we will use the abbv. cadr(write (cadr (list (list 'A 'B) (list 'C'D)))) |
Output:
BEST GEEKS (C D)


