-
Notifications
You must be signed in to change notification settings - Fork 136
X Seq
Seq is an eager, purely functional singly LinkedList. Seq consists of a head element and a self-recursive tail.
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).
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);
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]
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);
oops - my bad