Combining Literals Top VariablesLists, Strings, and Arrays Contents

Lists, Strings, and Arrays

Recall that the built-in function list is used to construct a list. A similar function, called array, is used to construct an array populated with the given elements:

    (array 1 "two" 'three)
    -> [1 two three]

while a function named allocate is used to allocate an array of the given size:

    (allocate 5)
    -> [0 0 0 0 0]

Note that the elements of an allocated array are initialized to zero.

The functions for manipulating lists, arrays, and strings are quite similar. In the following sections, we will use the term collection to stand for lists, arrays, and strings.

Comparing collections

The equal? function is used to compare two collections of the same type:

    (equal? (list 1 (array "23" 'hello)) (list 1 (array "23" 'hello)))
    -> #t

    (eq? (list 1 (array "23" 'hello)) (list 1 (array "23" 'hello)))
    -> #f

Note that the eq? function tests for pointer equality and thus fails when comparing two separate lists, even though they look similar.

Strings can be compared with the string-compare function. Assuming a lexigraphical ordering based upon the ASCII code, then a string compare of two strings, a and b, returns a negative number if a appears lexigraphically before b, returns zero if a and b are lexigraphically equal, and returns a positive number otherwise.

    (string-compare "abc" "bbc")
    -> -1

Extracting elements

You can pull out an item from a collection by using the getElement function. With getElement, you specify exactly which element you wish to extract. This specification is called an index. The first element of a collection has index 0, the second index 1, and so on. This concept of having the first element having an index of zero is known as zero-based counting, a common concept in Computer Science. Here is some code that extracts the first element of a list:

    (getElement (list "a" #t 7) 0)
    -> a

    (getElement (array "b" #f 11) 1)
    -> #f

    (getElement "howdy" 2)
    -> w

What happens if the index is too large?

    (getElement (list "a" #t 7) 3)
    EXCEPTION: generalException
    index (3) is too large

Not surprisingly, an error is generated. In Scam, as with many programming languages, an error is known as an exception.

As with Scheme, the built-in car and cdr functions returns the first item and the tail of a collection, respectively:

    (car (list 3 5 7))
    -> 3

    (cdr "howdy")
    -> owdy

    (cdr (array 2 4 6))
    -> [4 6]

    (car "bon jour")
    -> b

In addition to extracting elements of a collection, one can change the elements in a collection as well. For more information, please see the chapter on Assignment.

Combining Literals Top VariablesLists, Strings, and Arrays Contents