Monday, July 27, 2009

The List Data Structure -- Part2

Cons Cells


Lists in Lisp are not a primitive data type; they are built up from "cons cells". A cons cell is a memory object that consists of two parts. The left half holds the data while the right half points to another cons cell or to nil. There is an excellent description of cons on wikipedia. Other interesting articles are 1 2 3. The practical common lisp book is also a good read. Do note that practical common lisp as the name suggests uses common lisp but most of the functions in common lisp work in emacs lisp too.

;;5.4 Building Cons Cells and Lists
;; cons, list, make-list, append, number-sequence
;;

(setq x '(a b c))
(cons 'a '1)
(cons x '2)


(cons 'a ())
(cons 'a (cons 'b (cons 'c ())))

;; list is an easier way to create lists
(list 'a 'b 'c)
(list ?a ?b ?c)      ; See 2.3.3.1 in elisp reference manual
(list "A string" '(1 2 3) '(a b c))

(number-sequence 10)
(number-sequence 10 20)
(number-sequence 10 20 2)
(number-sequence 10 0 -2)

(number-sequence 10 20 -2)
(number-sequence 10 0 2)
(number-sequence 10 100 -2)

;;zero increment
(number-sequence 10 10 0)
(number-sequence 10 11 0)  ;; this function generates an error

(number-sequence 1.5 6 2)  ;; for floating numbers


setcar and setcdr


setcar and setcdr are the most primitive functions for manipulating lists.
;; 5.6 Modifying Existing List Structure
;; setcar, setcdr

;; See the diagram given in elisp reference manual 5.6.2
(setq x '(1 2))
(setcar x 4)
x

(setq x1 '(a b c))
(setq x2 (cons 'z (cdr x1)))
(setcar (cdr x1) 'foo)
x1
x2
(setcar x1 'baz)
x1
x2

;; setcdr
;;The lowest-level primitive for modifying a CDR is `setcdr':
(setq x '(1 2 3))
(setcdr x '(4))
x

Deletion


Deleting an element using setcdr.
;; delete an element from a list
;; See 5.6.2
(setq y '(1 2 3))
(setcdr y (cdr (cdr y)))
y

Insertion


Inserting an element into a list using setcdr
;; insert an element into a list
(setq z '(a b c))
(setcdr z (cons 'd (cdr z)))
z

Summary


The functions described here are :
cons, list, number-sequence
setcar, setcdr,

Functions described here and related functions:
Creating and managing sets using lists, association lists and rings is pretty easy once you get the hang of the list structure.

0 comments:

Post a Comment