Man

Development & AI | Alper Akgun

Learning emacs elisp 2/4 - Data types

August, 2023

This is a guide to learn by examples. There are two ways I run the commands.

Open a new buffer and run `C-x C-e` after each expression

Using interactive expression evaluation `M-x ielm`

Lists

;; Empty lists
'()
(list)
nil
(quote ("a" 1 nil t))
(make-list 3 0)
(number-sequence 5 "a")


`(0 ,pi x2)(0 3.141592 x2)
`(0 ,@ '(1 2) ,@ (list 3 4))

(eq '() (list)) ; t
(length '("a" "b")) ; 2

;; List operations
(cons "a" '("b" "c")) ; '("a" "b" "c")

(car '("a" "b" "c")) ; "a"
(cdr '("a" "b" "c")) ; ("b" "c")
(nth 3 '(0 1 2 3 4))
(nthcdr 3 '(0 1 2 3 4))
(last '("a" "b" "c")) ; "c"

(progn
  (let
    (my-list '(1 2 3))
  (push 2 my-list))

(setq numbers '(1 2 3))
(add-to-list 'numbers "a")
(message "%s" numbers)

(setq even-numbers '(1 3 5))
(add-to-ordered-list 'even-numbers 4)

(pop even-numbers) ;  remove first element and return it
(push 9 even-numbers) ; add to the beginning

(setcar even-numbers 0)

(vconcat [3 4] ["a" "b"])  ; join two vectors

(append (list 1 2) (list 3 4)) ; append to the list

(mapconcat 'number-to-string '(1 2 3) ",") ; "1,2,3"
(mapconcat 'number-to-string [1 2 3] ",") ; "1,2,3"


(member 4 even-numbers)
(memq 4 even-numbers)
(memql 4 even-numbers)

(remq 4 even-numbers)
(delq 3 even-numbers)
(delete-dups even-numbers)

(format "%s" (1 3 5))
            

Vectors

;; Vectors
[1 2 3] ; no evaluation
(vector 1 2 pi) ; elements are evaluated
(make-vector 5 "a") ; make a vector of given length
(fillarray (make-vector 5 nil) 1)
(length [1 2 3])

;; manipulate
(aref [1 2 3] 0) ; array read element
(progn (setq ar [1 2 3]) (aset ar 0 pi) ar) ; array set element
[8 [3 [2 9] c] 7 [4 "b"]] ; nested vector
            

Cons pair or alist

;; Cons pair
(cons 1 2) ; cell or cons
(cons nil nil)

(setq pairs (cons 3 9 4 16))
(car pairs) ; first element
(cdr pairs) ; last element

(equal (list "a" "b" "c") (cons "a" (cons "b" (cons "c" nil)))) ; t

(cons "a" "b")
'("a" . "b")
(quote ("a" . "b"))

(proper-list-p (cons nil nil)) ; proper list

(list (cons 1 1) (cons 2 4) (cons 3 9))
(setq squares '( (1 . 1) (2 . 4) (3 . 9)))

(alist-get 2 squares)
(assoc 2 squares)
(assq 2 squares)
(rassoc 2 squares)
(assoc-delete-all 2 squares)


;; Property Lists

(plist-get '(x 1 y 3) 'y) ; 3
(plist-put '(x 1 y 3) 'z 5)
(plist-member '(x 1 y 3) 'x)


;; Symbol Property Lists

(setplist 'ff '(a 1 b 2))

            

List function and iterations

(setq countries (list "Italy" "Austria" "Turkey"))
(reverse countries)
(nreverse countries)
(remove "Italy" countries)
(delete "Italy" countries)
(seq-min (number-sequence 1 9))

(mapcar 'upcase countries)
(mapc 'upcase countries)

(dotimes (i 3)
  (insert (number-to-string i)))

(dolist
    (n countries)
  (insert n))