Sunday, July 26, 2009

The List Data Structure -- Part1

The Sequence is a very important data structure in emacs lisp. Both lists and arrays are types of sequences.
  1. Sequences
    1. Lists & cons cells
    2. Arrays
      • Strings
      • Vectors
      • bool-vector
      • char-table

Functions List

The primary focus of this article is the list data structure which is also a core data structure for emacs lisp. The functions that I am going to describe are given below :-
listp, consp, null, 
car, cdr, caar, cdr, caddr, cdddr ...

Predicates on Lists

A Predicate is a Unary Function whose result represents the truth or falsehood of some condition. For instance the function (listp arg1) returns t if it's argument, arg1 is a list and it returns nil otherwise.
;;5.2 Predicates on Lists
;;  consp, atom, listp, nlistp, null
 (listp '(1 2))
 (listp '())
 (listp 120)
 (consp '(q . r)) ;(consp arg1) returns true if arg1 is a cons element
; To know more about cons refer to 5.4 in elisp reference manual

(consp '(a b c))
(consp nil)
(consp 'a)
(consp "hello")

;; Use null for lists and
;;   the function ,'not', for truth values
(null "Hello")  ; Not recommended
(null '(1 2 3)) ; This is good
(null ())       ; And so is this

Accessing Elements of Lists

In order to get the first element of the list we use (car list). In order to get the list of elements besides the first we use (cdr list). For more examples and short-cuts see the code given below,
;;5.3 Accessing elements of lists
;; car, cdr, caar, caddr, cdddr, ...

(setq my-list '(1 2 3 4 5 6 7))

(car my-list)
(cdr my-list)
(car (cdr my-list))
(cadr my-list)
(cdr (cdr my-list))
(cddr my-list) ; equivalent to (cdr (cdr my-list))
; Refer 5.3 of elisp reference manual


(cdddr my-list)
(nthcdr 3 my-list); same as  (cdddr my-list)) 

;; Note that all the functions discussed above are non-destructive

The behaviour of car, cdr on the empty list is a bit peculiar in the sense that both car and cdr of an empty list returns the empty list. Please note that () is equivalent to nil is equivalent to '() is equivalent to 'nil.
;; Behaviour of car,cdr on the empty list
(car ())
(cdr ())
(cdr (cdr (cdr ())))
(cadadr ())


The functions described in this article and other similar functions that can be looked up,
consp, atom, listp, nlistp, null
car, cdr, caar, cdr, caddr, cdddr ...
nthcdr, nth.


Post a Comment