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 following class methods:

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.

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 boolean equals (StringList L1, StringList L2)
Returns true if L1 and L2 have the same length and the same elements in the same order (sameness of elements is determined by the equals instance method of the String class); otherwise returns false. Note that the equals method behaves differently than == on lists, which determines if two list nodes were created by the same call to prepend. For instance, if L is the list [the,dog,barks], then L.equals(prepend("the",tail(L))) is true, but L == prepend("the",tail(L)) is false.

public static String toString (StringList L)
Returns a string representation of 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 Stringlist with elements "a", "cat", and "meows". If s is not the printed representation of a string list, signals an error.