Vectors and Lists
Create a vector literal:
Create a vector literal with elements of different types:
Create a nested vector:
Create a vector using a function:
Get the first element of a vector:
Get all elements except the first of a vector:
A sequence rather than a vector is returned.
Tet the third element of a vector:
To get to the nth element requires n-1 calls of rest, followed by a single
call of first. The nth function is more convenient (and faster):
The index is zero-based. The same can be achieved by using the vector like a function:
Add an element to the end of a vector:
The original vector is not modified, but a new, larger vector is created, sharing the common data with the original vector.
Add an element to the front of a vector:
Again, a sequence is returned, and the original vector is not modified.
Create a list literal:
Create a list using a function:
The leading ' can be left away for empty lists and within list literals:
Apply additional operations to a list:
Extend a list:
Applied to a list, both conj and cons add new elements to the front for
better efficiency.
Exercises
Accessing Elements
Given the following vector:
Write an expression that returns the element 8.
Hint: Use the first and rest functions.
Test: The element 8 is returned.
Extending a List
Given the following list:
Write an expression that appends the elements 0, 1, and 2 to the front of
the list.
Hint: Use the cons function.
Test: The sequence (0 1 2 3 4 5 6 7 8 9) is returned.
Extending a Vector
Given the following vector:
Write an expression that appends the elements 0, 1, and 2 to the front,
and the element 9 to the end.
Hint: Use the cons and conj functions. Unlike cons, conj returns a
vector.
Test: The sequence (0 1 2 3 4 5 6 7 8 9) is returned.