java-cons

This small, one interface project is a try to reimplement the mechanics used in Rackets cons cells in Java.
git clone git://git.oshgnacknak.de/java-cons.git
Log | Files | Refs | README

README (1789B)


      1 Java Cons
      2 =========
      3 
      4 This small, one interface project is a try to reimplement
      5 the mechanics used in Rackets cons cells in Java.
      6 A 'cons cell' is a immutable node of linked list, which implements
      7 the recursive application of functions to "modify" it.
      8 That is, create a cons cell with the new values in it.
      9 
     10 To create a cons cell one would just call e.g.
     11     Cons.of(1, 2, 3, 4, 5, 6);
     12 
     13 Similar to how (list 1 2 3 4 5 6) is a shortcut to
     14     (cons 1 (cons 2 (...))).
     15 
     16 Next the standard functions first and rest
     17 there is map, filter, foldl and foldr.
     18 These functions also use recursive application to create new cons cells.
     19 
     20 map transforms the elements of a cons cell based on a given 'mapper' function.
     21 For example:
     22     > Cons.of(1, 2, 3, 4).map(n -> n * n);
     23     Cons.of(1, 4, 9, 16)
     24 
     25 filter takes a so called 'predicate' - a function from the elements of a cons cell to boolean.
     26 It then creates a new cons cell with only the elements in the cons cell, that pass the predicate.
     27 For example:
     28     > Cons.of(1, 2, 3, 4).filter(n -> n % 2 == 1);
     29     Cons.of(1, 3)
     30 
     31 foldl and foldr both take a initial element and a function from that
     32 element and an element of the cons cell to a value of the same type as the first one given.
     33 This is often used to reduce the elements of a cons cell to a single value.
     34 For example:
     35     > Cons.of(1, 2, 3, 4).foldl((a, b) -> a + b, 0);
     36     10
     37 However there is a difference between the order of applications of foldl and foldr:
     38 
     39 That is, foldl looks like this:
     40     f(f(f(f(f init x0) x1) x2) x3)
     41 where as foldr looks like this:
     42     f(x0 f(x1 f(x2 f(x3 init))))
     43 
     44 A difference can be seen in this example:
     45     > Cons.of("Hello", "World").foldl((a, b) -> a.concat(b), "");
     46     WeltHallo
     47     > Cons.of("Hello", "World").foldr((a, b) -> a.concat(b), "");
     48     HalloWelt