Skip to content
John McClean edited this page Sep 17, 2018 · 2 revisions

Seq

Seq is an eager, purely functional singly LinkedList. Seq consists of a head element and a self-recursive tail.

class diagrams-seq

Each node consists either of a Cons (which represents a value that is present) or Nil which represents the termination of the List (an empty Seq is just a Nil node).

class diagrams-seq 1

Usage

Seq instances can be created via creational methods such as of, generate, fill and iterate. E.g.

Seq<Integer> list = Seq.of(1,2,3);

Like LazySeq, Vector, LazyString, IntMap, DifferenceList and NonEmptyList Seq implements ImmutableList.

ImmutableList<Integer> imList = Seq.of(10,20,30);

Safe APIs

Unlike the Java Collection APIs Seq will not allow users to perform operations directly that might throw an exception - for example it is not possible to call 'head' (extract the first value) on an Empty Seq, instead we can use an overloaded method that accepts a default such as headOrElse, or a fold.

E.g. in the example below first is assigned to 1

Integer first = Seq.of(1,2,3)
                   .headOrElse(-1);

Similarly extracting a value at a given index returns an Option type, if an out-of-range index is specified Option.none is returned.

Option<Integer> opt = Seq.of(1,2,3)
                         .get(1000);
//opt None

For updates and deletions set & deletions can be used that will return an Either that captures an error type when out-of-bounds changes are performed. The updated Seq is returned as the default / right sided type, or the actual size of the Seq is returned in the out-of-bounds case as the left sided Either.

Either<Integer,Seq<Integer> delete = Seq.of(1,2,3)
                                        .delete(1000);
//delete Either[3]

removeAt and deleteAt are equivalent methods that simply return a Seq, if the index supplied is out-of-bounds, the Seq is returned unchanged

Seq<Integer> remove = Seq.of(1,2,3)
                         .removeAt(1000);
//remove Seq[1,2,3]

Pattern Matching on Seq

We can use the pattern matching API to safely extract values from a Seq

Seq<Integer> list = Seq.of(1,2,3);
int first = MatchType(list).with(Case(nel->nel.head()),
                                 Case(empty->-1));

int first2 = list.fold(s->s.head(),e->-1);
Clone this wiki locally