Elisp: Variables, Booleans and Lists

☕️ 2 min read

In Elisp is a common approach to use dashes - to define variables and functions names.

Number

Set multiple numeric variables:

(setq my-var 90 my-other-var 10)
(+ my-var my-other-var)

Output:

100

Boolean

Truthy

By convention, the symbol t is used for true cases like the following:

(if t "yes" "no") ; "yes"
(if 0 "yes" "no") ; "yes"
(if "" "yes" "no") ; "yes"
(if [] "yes" "no") ; "yes". The [] is vector of 0 elements

Output:

yes

Falsy

In elisp, the symbol nil is false, anything else is true. Also, nil is equivalent to the empty list (), so () is also false. See some examples:

(if nil "yes" "no") ; "no"
(if () "yes" "no") ; "no"
(if '() "yes" "no") ; "no"
(if (list) "yes" "no") ; "no", because (list) eval to a empty list, same as ()

Output:

no

Lists

Let’s define a list:

(setq my-list '(1 2 3 4))

Output:

1 2 3 4

Add number 5 to the my-list:

(add-to-list 'my-list 5)

Output:

5 1 2 3 4

Create a new list with number 6 using cons:

(cons 6 my-list)
my-list

Output my-list:

5 1 2 3 4

Output new list:

6 5 1 2 3 4

Get the first element the list:

(car my-list)

Output:

5

Get the rest of the list after first element:

(cdr my-list)

Output:

1 2 3 4

Get element from specific index:

(nth 2 my-list)

Output:

2

Note: The list starts from index 0 and the value from 0 is 5

Let’s define a method to find if exists an index and return values start from it:

(defun does-exists (number some-list)
  (member number some-list))
(does-exists 2 my-list)

Output:

2 3 4

The test of does-exists method:

(require 'ert)
(ert-deftest check-number ()
  (should (does-exists 2 '(2 3 4))))

Output:

check-number

Check if index don’t exists:

(ert-deftest check-not-found-number ()
  (should (not (does-exists 6 '(2 3 4)))))

Output:

check-not-found-number

Note: To eval the tests run M-x + ert

References