commit f2cd791f6e84b2b11ae4c9b261ad036b08dd0fd6
parent 8783d82a0b23e924b0afe0b8034619a5babeef1c
Author: Oshgnacknak <osh@oshgnacknak.de>
Date: Fri, 15 Jan 2021 00:16:02 +0100
Add README
Diffstat:
3 files changed, 53 insertions(+), 1 deletion(-)
diff --git a/.gitignore b/.gitignore
@@ -0,0 +1,3 @@
+/out/
+/.idea/
+/cons.iml
diff --git a/README b/README
@@ -0,0 +1,48 @@
+Java Cons
+=========
+
+This small, one interface project is a try to reimplement
+the mechanics used in Rackets cons cells in Java.
+A 'cons cell' is a immutable node of linked list, which implements
+the recursive application of functions to "modify" it.
+That is, create a cons cell with the new values in it.
+
+To create a cons cell one would just call e.g.
+ Cons.of(1, 2, 3, 4, 5, 6);
+
+Similar to how (list 1 2 3 4 5 6) is a shortcut to
+ (cons 1 (cons 2 (...))).
+
+Next the standard functions first and rest
+there is map, filter, foldl and foldr.
+These functions also use recursive application to create new cons cells.
+
+map transforms the elements of a cons cell based on a given 'mapper' function.
+For example:
+ > Cons.of(1, 2, 3, 4).map(n -> n * n);
+ Cons.of(1, 4, 9, 16)
+
+filter takes a so called 'predicate' - a function from the elements of a cons cell to boolean.
+It then creates a new cons cell with only the elements in the cons cell, that pass the predicate.
+For example:
+ > Cons.of(1, 2, 3, 4).filter(n -> n % 2 == 1);
+ Cons.of(1, 3)
+
+foldl and foldr both take a initial element and a function from that
+element and an element of the cons cell to a value of the same type as the first one given.
+This is often used to reduce the elements of a cons cell to a single value.
+For example:
+ > Cons.of(1, 2, 3, 4).foldl((a, b) -> a + b, 0);
+ 10
+However there is a difference between the order of applications of foldl and foldr:
+
+That is, foldl looks like this:
+ f(f(f(f(f init x0) x1) x2) x3)
+where as foldr looks like this:
+ f(x0 f(x1 f(x2 f(x3 init))))
+
+A difference can be seen in this example:
+ > Cons.of("Hello", "World").foldl((a, b) -> a.concat(b), "");
+ WeltHallo
+ > Cons.of("Hello", "World").foldr((a, b) -> a.concat(b), "");
+ HalloWelt+
\ No newline at end of file
diff --git a/src/NonEmptyTest.java b/src/NonEmptyTest.java
@@ -60,7 +60,7 @@ class NonEmptyTest {
var expected = "(cons 1 (cons 2 (cons 3 empty)))";
assertEquals(expected, cons.toString());
- expected = "(cons Hallo (cons empty))";
+ expected = "(cons Hallo (cons Welt empty))";
assertEquals(expected, stringCons.toString());
}
}
\ No newline at end of file