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 'w3wiki ' 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:
(w3wiki . 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 'w3wiki' nil )) (terpri) ; list with a cons as an argument (write ( list 3 4 'Beginner (car ' (G . F)) ( * 99 + 78 ))) (terpri) ; list with another list as an argument (write ( list ( list 'w3wiki ' is) ( list 'the ' best 'resource ' for 'DSA))) |
Output:
(1 2) (G E E K S) (w3wiki NIL) (3 4 Beginner G 7722) ((w3wiki 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 car and cdr can be abbreviated as cadadr/caar/cadr and so on.
Example:
Lisp
; here we will extract the string Best (write (cadadr '(w3wiki (is best) (for Data Structures)))) (terpri) ; here we will extract the string Beginner (write (caar ( list ( list 'Beginner ' for) 'Beginner))) (terpri) ; here we will use the abbv. cadr (write (cadr ( list ( list 'A ' B) ( list 'C' D)))) |
Output:
BEST Beginner (C D)
Contact Us