Build lists in mathematical set-builder notation with Java, like { x * 2 | x E {1,2} ^ x is even }.
Used at: :D https://github.com/farolfo/JComprehension
In algebra we are able to define sets using set-builder notation, also known as set comprehension or list comprehension. For example, this computes the even numbers in a set of integers
{ x | x E {1,2,3,4} ^ x is even }
// gives {2,4}
which is read as give me the set of all x such that x belongs to {1,2,3,4} and x is even.
But this notation jumped out of algebra and today we have ways to do this in many programming languages, such as Haskell or python.
Now you can achieve this in Java
Predicate<Integer> even = x -> x % 2 == 0;
List<Integer> evens = new ListComprehension<Integer>()
.suchThat(x -> {
x.belongsTo(Arrays.asList(1, 2, 3, 4));
x.is(even);
});
// evens = {2,4};
And if we want to transform the output expression in some way like
{ x * 2 | x E {1,2,3,4} ^ x is even }
// gives {4,8}
Our java code would look like
List<Integer> duplicated = new ListComprehension<Integer>()
.giveMeAll((Integer x) -> x * 2)
.suchThat(x -> {
x.belongsTo(Arrays.asList(1, 2, 3, 4));
x.is(even);
});
// duplicated = {4,8}
- Set-builder notation.
- How are programming languages supporting this today?
- Haskell's list comprehension
MIT