CS111 StringList Contract

The StringList class describes immutable linked lists of strings. A string list is defined recursively as either

String lists are immutable in the sense that the head or tail of a list node cannot be changed after the list node has been created (via the prepend() method).

There are no public constructor or instance methods for string lists; they are created and manipulated by the class methods below. By default, an IntList class method is invoked via StringList.methodName(args), but this can be abbreviated to SL.methodName(args) by including the following "magical" declaration in the body of a class:

public static StringList SL; // declare but never initialize this variable.

Class Methods

public static StringList empty()
Returns an empty string list.

public static StringList prepend (String s, StringList L)
Returns a new string list node whose head is s and whose tail is L. From another perspective, returns a list whose length is one more than the length of L and whose elements are s followed by the elements of L, in order.

public static boolean isEmpty (StringList L)
Returns true if L is an empty string list and false if L is an string list node.

public static String head (StringList L)
Returns the string that is the head component of the string list node L. Signals an exception if L is empty.

public static StringList tail (StringList L)
Returns the string list that is the tail component of the string list node L. Signals an exception if L is empty.

public static String toString (StringList L)
Returns a string representation of the string list L in which the string elements are separated by commas and delimited by square brackets. The individual string elements are not delimited by quotation marks in this printed representation. For example, if L1 is a list containing the sequence of strings "the", "dog", and "barks", then toString(L1) returns "[the,dog,barks]".

public static StringList fromString (String s)
If s is the printed representation of a string list (i.e., comma separated strings delimited by square brackets), returns a StringList with that representation. For example, fromString("[a,cat,meows]") returns a 3-element integer list with elements "a", "cat", and "meows". If s is not the printed representation of a string list, signals an error.