-
Notifications
You must be signed in to change notification settings - Fork 2
pair
TurtleKitty edited this page May 10, 2019
·
4 revisions
The humble pair is the simplest compound data structure in Vaquero. It consists of two values - a head and a tail.
A list is a pair whose tail is either another pair or the empty list (). The empty list () is evaluates to itself.
(pair 2 3) ; (2 . 3)
(pair 2 (pair 3 (pair 5 ()))) ; (2 3 5)
(list 2 3 5) ; (2 3 5)
(quote (2 3 5)) ; (2 3 5)
'(2 3 5) ; (2 3 5)
() ; ()
Pairs and lists are fundamental to all Lisp dialects; the code itself is composed of them.
(pair? x) -> returns true if x is a pair or a list with size > 0.
(list? x) -> returns true if x is a proper list (a series of pairs ending in ()) or the empty list ().
(def p (pair 2 3))
(def xs (list 3 4 5))
(pair? p) ; true
(list? p) ; false
(pair? xs) ; true
(list? xs) ; true
(pair? ()) ; false
(list? ()) ; true
(def coin (pair 0 1))
(def primes (list 2 3 5 7 11))
(def empty ())
coin.type ; (pair)
primes.type ; (list pair)
coin.head ; 0
coin.tail ; 1
coin.key ; 0
coin.val ; 1
primes.head ; 2
primes.tail ; (3 5 7 11)
empty.head ; null
empty.tail ; null
coin.size ; 2
primes.size ; 5
empty.size ; 0
; multiple ways to get at list contents
; list objects answer the 'apply message, so they can be used like procedures
primes.0 ; 2
(primes 1) ; 3
(send primes 2) ; 5
coin.to-bool ; true
primes.to-bool ; true
empty.to-bool ; false
coin.clone ; (0 . 1)
primes.clone ; (2 3 5 7 11)
(= primes primes.clone) ; true
(is? primes primes.clone) ; false
; mutation
coin ; (0 . 1)
(coin.head! 1) ; 1
(coin.tail! 2) ; 2
coin ; (1 . 2)
; proper-list-only messages
primes.empty? ; false
empty.empty? ; true
(primes.append '(13 17)) ; (2 3 5 7 11 13 17)
(primes.apply '(3)) ; 7
(primes.has? 11) ; true
(primes.has? 0) ; false
(def composites '(4 6 8 9 oops))
(composites.set! 4 10) ; 10
composites ; (4 6 8 9 10)
(primes.take 3) ; (2 3 5)
(primes.drop 3) ; (7 11)
primes.reverse ; (11 7 5 3 2)
primes.to-set ; #(set 11 7 5 3 2)
primes.to-vector ; #(vector 2 3 5 7 11)
; association lists can be converted to tables
(def list-of-pairs '((foo . 2) (bar . 3) (baz . 5)))
list-of-pairs.to-table ; #(table bar 3 baz 5 foo 2)