This article is in continuation with articles serie on functional programming paradigm which started with the following one.

## Representing data through functions

Let `S`

be any set of elements `a`

, `b`

, `c`

... (for instance the books on the table or the points of the euclidean plane) and let `S'`

be any subset of these elements (for instance the green books on the table or the points in the circle of radius 1 centered at the origin of the Euclidean plane).

The Characteristic Function `S'(x)`

of the set `S'`

is a function which associates either `true`

or `false`

with each element `x`

of `S`

.

```
S'(x) = true if x is in S'
S'(x) = false if x is not in S'
```

Let `S`

be the set of books on the table and let `S'`

be the set of green books on the table. Let `a`

and `b`

be two green books, and let `c`

and `d`

be two red books on the table. Then:

```
S'(a) = S'(b) = true
S'(c) = S'(d) = false
```

Let `S`

be the set of the points in the euclidean plane and let `S'`

be the set of the points in the circle of radius 1 centered at the origin of the euclidean plane (0, 0) (unit circle). Let `a`

and `b`

be two points in the unit circle, and let `c`

and `d`

be two points in a circle of radius 2 centered at the origin of the euclidean plane. Then:

```
S'(a) = S'(b) = true
S'(c) = S'(d) = false
```

Thus, any set `S'`

can always be represented by its characteristic function. A function that takes as argument an element and returns `true`

if this element is in `S'`

, `false`

otherwise. In other words, a set (abstract data type) can be represented through a Predicate in Java.

`Predicate<T> set;`

In the next sections, we will see how to represent some fundamental sets in the algebra of sets through Java in a functional way, then we will define generic binary operations on sets. We will then apply these operations on numbers then on subsets of the euclidean plane. Sets are abstract data structures, the subsets of numbers and the subsets of the euclidean plane are the representation of abstract data-structures, and finally the binary operations are the generic logics that works on any representation of the abstract data structures.

### Sets

This section introduces the representation of some fundamental sets in the algebra of sets through Java.

#### Empty set

Let `E`

be the empty set and `Empty`

its *Characteristic function*. In algebra of sets, `E`

is the unique set having no elements. Therefore, `Empty`

can be defined as follows:

```
Empty(x) = false if x is in E
Empty(x) = false if x is not in E
```

Thus, the representation of `E`

in Java can be defined as follows:

```
public static <T> Predicate<T> empty(){
return x -> false;
}
```

In algebra of sets, `Empty`

is represented as follows:

Thus, running the code below:

```
System.out.println("\nEmpty set:");
System.out.println("Is 7 in {}? " + empty().test(7));
```

gives the following results:

#### Set All

Let `S`

be a set and `S'`

be the subset of `S`

that contains all the elements and `All`

its *Characteristic function*. In algebra of sets,`S'`

is the full set that contains all the elements. Therefore, `All`

can be defined like this:

`All(x) = true if x is in S`

Thus, the representation of `S'`

in Java can be defined as follows:

```
public static <T> Predicate<T> all(){
return x -> true;
}
```

In algebra of sets, `All`

is represented as follows:

Thus, running the code below:

`System.out.println("Is 7 in the integers set ? " + all().test(7));`

gives the following results:

#### Singleton set

Let `E`

be the Singleton set and `Singleton`

its *Characteristic function*. In algebra of sets, `E`

also known as unit set, or 1-tuple is a set with exactly one element `e`

. Therefore, `Singleton`

can be defined as follows:

```
Singleton(x) = true if x is e
Singleton(x) = false if x is not e
```

Thus, the representation of `E`

in Java can be defined as follows:

```
public static <T> Predicate<T> singleton(T e){
return x -> x.equals(e);
}
```

Thus, running the code below:

```
System.out.println("Is 7 in the singleton {0}? " + singleton(0).test(7));
System.out.println("Is 7 in the singleton {7}? " + singleton(7).test(7));
```

gives the following results:

#### Other sets

This section presents subsets of the integers set.

##### Even numbers

Let `E`

be the set of even numbers and `Even`

its *Characteristic function*. In mathematics, an even number is a number which is a multiple of two. Therefore, `Even`

can be defined as follows:

```
Even(x) = true if x is a multiple of 2
Even(x) = false if x is not a multiple of 2
```

Thus, the representation of `E`

in Java can be defined as follows:

`Predicate<Integer> even = i -> i%2 == 0;`

Thus, running the code below:

```
System.out.println("Is 99 even? " + even.test(99));
System.out.println("Is 998 even? " + even.test(998));
```

gives the following results:

##### Odd numbers

Let `E`

be the set of odd numbers and `Odd`

its *Characteristic function*. In mathematics, an odd number is a number which is not a multiple of two. Therefore, `Odd`

can be defined as follows:

```
Odd(x) = true if x is not a multiple of 2
Odd(x) = false if x is a multiple of 2
```

Thus, the representation of `E`

in Java can be defined as follows:

`Predicate<Integer> odd = i -> i%2 == 1;`

Thus, running the code below:

```
System.out.println("Is 99 odd? " + odd.test(99));
System.out.println("Is 998 odd? " + odd.test(998));
```

gives the following results:

##### Multiples of 3

Let `E`

be the set of multiples of 3 and `MultipleOfThree`

its *Characteristic function*. In mathematics, a multiple of 3 is a number divisible by 3. Therefore, `MultipleOfThree`

can be defined as follows:

```
MultipleOfThree(x) = true if x is divisible by 3
MultipleOfThree(x) = false if x is not divisible by 3
```

Thus, the representation of `E`

in Java can be defined as follows:

`Predicate<Integer> multipleOfThree = i -> i%3 == 0;`

Thus, running the code below:

```
System.out.println("Is 99 a multiple of 3? " + multipleOfThree.test(99));
System.out.println("Is 998 a multiple of 3? " + multipleOfThree.test(998));
```

gives the following results:

##### Multiples of 5

Let `E`

be the set of multiples of 5 and `MultipleOfFive`

its *Characteristic function*. In mathematics, a multiple of 5 is a number divisible by 5. Therefore, `MultipleOfFive`

can be defined as follows:

```
MultipleOfFive(x) = true if x is divisible by 5
MultipleOfFive(x) = false if x is not divisible by 5
```

Thus, the representation of `E`

in Java can be defined as follows:

`Predicate<Integer> multipleOfFive = i -> i%5 == 0;`

Thus, running the code below:

```
System.out.println("Is 15 a multiple of 5? " + multipleOfFive.test(15));
System.out.println("Is 998 a multiple of 5? " + multipleOfFive.test(998));
```

gives the following results:

##### Prime numbers

A long time ago, When I was playing with Project Euler problems, I had to resolve the following one:

```
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?
```

To resolve this problem, I first had to write a fast algorithm that checks whether a given number is prime or not. Once the algorithm written, I wrote an iterative algorithm that iterates through primes until the 10 001st prime number was found.

Let `E`

be the set of primes and `Prime`

its *Characteristic function*. In mathematics, a prime is a natural number greater than 1 that has no positive divisors other than 1 and itself. Therefore, `Prime`

can be defined as follows:

```
Prime(x) = true if x is prime
Prime(x) = false if x is not prime
```

Thus, the representation of `E`

in Java can be defined as follows:

`Predicate<Integer> prime = x -> isPrime(x);`

where `isPrime`

is a method that checks whether a given number is prime or not.

```
public static Boolean isPrime(int i){
if (i <= 1) return false;
if (i < 4) return true; // 2 and 3 are primes
if (i % 2 == 0) return false; // multiples of 2 are not prime
if (i < 9) return true; // 5 and 7 are primes
if (i % 3 == 0) return false; // multiples of 3 are not primes
// If a divisor less than or equal to sqrt(i) is found
// then i is not prime
int sqrt = (int)Math.sqrt(i);
for (int d = 5; d <= sqrt; d += 6){
if (i % d == 0) return false;
if (i % (d + 2) == 0) return false;
}
// Otherwise i is prime
return true;
}
```

Thus, running the code below to resolve our problem:

```
int p = getPrime(10001, prime);
System.out.println("The 10 001st prime number is " + p);
```

where `getPrime`

is defined below:

```
public static int getPrime (int p, Predicate<Integer> prime){
for(int i = 1, count = 0; ; i++){
if(prime.test(i)) count++;
if(count == p) return i;
}
}
```

gives the following results:

### Binary operations

This section presents several fundamental operations for constructing new sets from given sets and for manipulating sets. Below the Ven diagram in the algebra of sets.

#### Union

Let `E`

and `F`

be two sets. The *union* of `E`

and `F`

, denoted by `E U F`

is the set of all elements wich are members of either `E`

and`F`

.

Let `Union`

be the *union* operation. Thus, the `Union`

operation can be implemented as follows in Java:

```
public static <T> Predicate<T> union(Predicate<T> e, Predicate<T> f){
return x -> e.test(x) || f.test(x);
}
```

Running the code below:

`System.out.println("Is 7 in the union of Even and Odd sets? " + BinaryOperation.union(even, odd).test(7));`

gives the following results:

#### Intersection

Let `E`

and `F`

be two sets. The *intersection* of `E`

and `F`

, denoted by `E n F`

is the set of all elements wich are members of both`E`

and `F`

.

Let `Intersection`

be the *intersection* operation. Thus, the `Intersection`

operation can be implemented as follows in Java:

```
public static <T> Predicate<T> intersection(Predicate<T> e, Predicate<T> f){
return x -> e.test(x) && f.test(x);
}
```

Running the code below:

```
Predicate<Integer> multiplesOfThreeAndFive = BinaryOperation.intersection(multipleOfThree, multipleOfFive);
System.out.println("Is 15 a multiple of 3 and 5? " + multiplesOfThreeAndFive.test(15));
System.out.println("Is 10 a multiple of 3 and 5? " + multiplesOfThreeAndFive.test(10));
```

gives the following results:

#### Cartesian product

Let `E`

and `F`

be two sets. The *cartesian product* of `E`

and `F`

, denoted by `E × F`

is the set of all ordered pairs `(e, f)`

such that `e`

is a member of `E`

and `f`

is a member of `F`

.

Let `CartesianProduct`

be the *cartesian product* operation. Thus, the `CartesianProduct`

operation can be implemented as follows in Java:

```
public static <T1, T2> BiFunction<T1, T2, Boolean> cartesianProduct(Predicate<T1> e, Predicate<T2> f){
return (x, y) -> e.test(x) && f.test(y);
}
```

Running the code below:

```
BiFunction<Integer, Integer, Boolean> cartesianProduct = BinaryOperation.cartesianProduct(multipleOfThree, multipleOfFive);
System.out.println("Is (9, 15) in MultipleOfThree x MultipleOfFive? " + cartesianProduct.apply(9, 15));
```

gives the following results:

#### Complements

Let `E`

and `F`

be two sets. The *relative complement* of `F`

in `E`

, denoted by `E \ F`

is the set of all elements wich are members of `E`

but not members of `F`

.

Let `Complement`

be the *relative complement* operation. Thus, the `Complement`

operation can be implemented as follows in Java:

```
public static <T> Predicate<T> complement(Predicate<T> e, Predicate<T> f){
return x -> e.test(x) && !f.test(x);
}
```

Running the code below:

```
Predicate<Integer> multipleofThreeAndNotFive = BinaryOperation.complement(multipleOfThree, multipleOfFive);
System.out.println("Is 15 in MultipleOfThree \\ MultipleOfFive set? " + multipleofThreeAndNotFive.test(15));
System.out.println("Is 9 in MultipleOfThree \\ MultipleOfFive set? " + multipleofThreeAndNotFive.test(9));
```

gives the following results:

#### Symmetric Difference

Let `E`

and `F`

be two sets. The *symmetric difference* of `E`

and `F`

, denoted by `E ? F`

is the set of all elements wich are members of either `E`

and `F`

but not in the intersection of `E`

and `F`

.

Let `SymmetricDifference`

be the *symmetric difference* operation. Thus, the `SymmetricDifference`

operation can be implemented in two ways in Java. A trivial way is to use the union and complement operations as follows:

```
public static <T> Predicate<T> symmetricDifferenceWithoutXor(Predicate<T> e, Predicate<T> f){
return union(complement(e, f), complement(f, e));
}
```

Another way is to use the `XOR`

binary operation as follows:

```
public static <T> Predicate<T> symmetricDifferenceWithXor(Predicate<T> e, Predicate<T> f){
return x -> e.test(x) ^ f.test(x);
}
```

Running the code below:

```
// SymmetricDifference without XOR
System.out.println("\nSymmetricDifference without XOR:");
Predicate<Integer> sdWithoutXor = BinaryOperation.symmetricDifferenceWithoutXor(prime, even);
System.out.println("Is 2 in the symetric difference of prime and even Sets? " + sdWithoutXor.test(2));
System.out.println("Is 4 in the symetric difference of prime and even Sets? " + sdWithoutXor.test(4));
System.out.println("Is 7 in the symetric difference of prime and even Sets? " + sdWithoutXor.test(7));
// SymmetricDifference with XOR
System.out.println("\nSymmetricDifference with XOR:");
Predicate<Integer> sdWithXor = BinaryOperation.symmetricDifferenceWithXor(prime, even);
System.out.println("Is 2 in the symetric difference of prime and even Sets? " + sdWithXor.test(2));
System.out.println("Is 4 in the symetric difference of prime and even Sets? " + sdWithXor.test(4));
System.out.println("Is 7 in the symetric difference of prime and even Sets? " + sdWithXor.test(7));
```

gives the following results:

#### Other operations

This section presents other useful binary operations on sets.

##### Contains

Let `Contains`

be the operation that checks whether or not an element is in a set. This operation takes as parameter an element and returns `true`

if the element is in the set, `false `

otherwise.

Thus, this operation is defined as follows in Java:

```
public static <T> Boolean contains(Predicate<T> e, T x){
return e.test(x);
}
```

Therefore, running the code below:

```
System.out.println("Is 7 in the singleton {0}? " + BinaryOperation.contains(singleton(0), 7));
System.out.println("Is 7 in the singleton {7}? " + BinaryOperation.contains(singleton(7), 7));
```

gives the following result:

##### Add

Let `Add`

be the operation that adds an element to a set. This operation takes as parameter an element and adds it to a set.

Thus, this operation is defined as follows in Java:

```
public static <T> Predicate<T> add(Predicate<T> s, T e){
return x -> x.equals(e) || s.test(x);
}
```

Therefore, running the code below:

```
System.out.println("Is 7 in {0, 7}? " + BinaryOperation.add(singleton(0), 7).test(7));
System.out.println("Is 0 in {1, 0}? " + BinaryOperation.add(singleton(1), 0).test(0));
System.out.println("Is 7 in {19, 0}? " + BinaryOperation.add(singleton(19), 0).test(7));
```

gives the following result:

##### Remove

Let `Remove`

be the operation that removes an element from a set. This operations takes as parameter an element and removes it from a set.

Thus, this operation is defined as follows in Java:

```
public static <T> Predicate<T> remove(Predicate<T> s, T e){
return x -> !x.equals(e) && s.test(x);
}
```

Therefore, running the code below:

```
System.out.println("Is 7 in {}? " + BinaryOperation.remove(singleton(0), 0).test(7));
System.out.println("Is 0 in {}? " + BinaryOperation.remove(singleton(7), 7).test(0));
```

gives the following result:

### For those who want to go further

You can see how easy we can do some algebra of sets in Java through functional programming. In the previous sections was shown the most fundamental definitions. But, If you want to go further, you can think about:

- Relations over sets
- Abstract algebra, such as monoids, groups, fields, rings, K-vectorial spaces and so on
- Inclusion-exclusion principle
- Russell's paradox
- Cantor's paradox
- Dual vector space
- Theorems and Corollaries

## Euclidean Plane

In the previous section, the fundamental concepts on sets were implemented in Java. In this section we will practice the concepts implemented on the set of plane points (Euclidean plane).

### Drawing a disk

A disk is a subset of a plane bounded by a circle. There are two types of disks. *Closed* disks which are disks that contain the points of the circle that constitutes its boundary, and *Open* disks wich are disks that do not contain the points of the circle that constitutes its boundary.

In this section, we will set up the *Characterstic function* of the *Closed* disk and draw it in a JavaFX façade.

To set up the *Characterstic function* we need first a function that calculates the *Euclidean Distance* between two points in the plane. This function is implemented as follows:

```
public static double euclidianDistance(Point point1, Point point2){
return Math.sqrt(Math.pow(point1.getX() - point2.getX(), 2) + Math.pow(point1.getY() - point2.getY(), 2));
}
```

where `Point`

is defined below.

```
package functional.plane;
public class Point {
private double x;
private double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
}
```

The formula is based on Pythagoras' Theorem.

where `c`

is the *Euclidean distance*, `a²`

is `(point1.X - point2.X)²`

and `b²`

is `(point1.Y - point2.Y)²`

.

Let `Disk`

be the *Characteristic function* of a closed disk. In algebra of sets, the definition of a closed disk in the reals set is as follows:

where `a`

and `b`

are the coordinates of the center and `R`

the radius.

Thus, the implementation of `Disk`

in Java is as follows:

```
public static Predicate<Point> disk(Point center, double radius){
return p -> euclidianDistance(center, p) <= radius;
}
```

In order to view the set in a façade, I decided to implement a function `draw`

that draws a set in the *Euclidean plane*. I chose JavaFX and thus used the `javafx.scene.canvas.Canvas`

.

Thus, I've built the *Euclidean plane* illustrated below through the method `draw`

.

Below the implementation of the method.

```
private static double CANVAS_WIDTH = 300;
private static double CANVAS_HEIGHT = 250;
private void draw(GraphicsContext gc, Predicate<Point> set) {
double semiWidth = CANVAS_WIDTH/2, semiHeight = CANVAS_HEIGHT/2,
xMin = -semiWidth, xMax = semiWidth,
yMin = -semiHeight, yMax = semiHeight;
gc.clearRect(0, 0, CANVAS_WIDTH, CANVAS_HEIGHT);
for(int x = 0; x < CANVAS_WIDTH; x++){
double xp = xMin + x * (xMax - xMin) / CANVAS_WIDTH;
for(int y = 0; y < CANVAS_HEIGHT; y++) {
double yp = yMax - y * (yMax - yMin) / CANVAS_HEIGHT;
if(set.test(new Point(xp, yp))) gc.fillRect(x, y, 1, 1);
}
}
}
```

In the `draw`

method, a `canvas`

having the same width and same height as the *Euclidean plane* container is created. Then each point in pixels `(x,y)`

of the `canvas`

is replaced by a black point if it belongs to the `set`

. `xMin`

, `xMax`

, `yMin`

and `yMax `

are the bounding values illustrated in the figure of the *Euclidean plane* above.

Running the code below.

```
Canvas canvas = new Canvas(CANVAS_WIDTH, CANVAS_HEIGHT);
GraphicsContext gc = canvas.getGraphicsContext2D();
draw(gc, disk(new Point(0, 0), 50));
```

gives the following façade:

### Drawing horizontal and vertical half-planes

A *horizontal* or a *vertical* half-plane is either of the two subsets into which a plane divides the Euclidean space. A *horizontal *half-plane is either of the two subsets into which a plane divides the Euclidean space through a line perpendicular with the *Y axis* like in the figure above. A *vertical* half-plane is either of the two subsets into which a plane divides the Euclidean space through a line perpendicular with the *X axis*.

In this section, we will set up the *Characteristic functions* of the *horizontal* and *vertical* half-planes, draw them in a JavaFX façade and see what we can do if we combine them with the *disk* subset.

Let `HorizontalHalfPlane`

be the *Characteristic function* of a *horizontal* half-plane. The implementation of `HorizontalHalfPlane`

in Java is as follows:

```
public static Predicate<Point> horizontalHalfPlane(double y, Boolean lowerThan){
return p -> lowerThan ? p.getY() <= y : p.getY() >= y;
}
```

Thus, running the code below:

`draw(gc, horizontalHalfPlane(0, true));`

gives the following façade:

Let `VerticalHalfPlane`

be the *Characteristic function* of a *vertical* half-plane. The implementation of `VerticalHalfPlane`

in Java is as follows:

```
public static Predicate<Point> verticalHalfPlane(double x, Boolean lowerThan){
return p -> lowerThan ? p.getX() <= x : p.getX() >= x;
}
```

Thus, running the code below:

`draw(gc, verticalHalfPlane(0, false));`

gives the following façade:

In the beginning of the article we've set up basic binary operations on sets. Thus, by combining the intersection of a `disk`

and a `half-plane`

for example, we can draw the half-disk subset.

Therefore, running the sample below:

`draw(gc, BinaryOperation.intersection(verticalHalfPlane(0, false), disk(new Point(0, 0), 50)));`

gives the following façade:

### Functions

This section presents functions on the sets in the Euclidean plane.

#### Translate

Let `Translate`

be the function that translates a point in the plane. In Euclidean geometry, `Translate`

is a function that moves a given point a constant distance in a specified direction. Thus the implementation in Java is as follows:

```
public static Function<Point, Point> translate(double deltax, double deltay){
return p -> new Point(p.getX() + deltax, p.getY() + deltay);
}
```

where `(deltax, deltay)`

is the constant vector of the translation.

Let `Translate`

be the function that translates a set in the plane. This function is simply implemented as follows in Java:

```
public static Predicate<Point> translate(Predicate<Point> set, double deltax, double deltay){
return x -> set.test(translate(-deltax, -deltay).apply(x));
}
```

`Translate`

takes as parameters `deltax`

which is the delta distance in the first Euclidean dimension and `deltay`

which is the delta distance in the second Euclidean dimension. If a point *P (x, y)* is translated in a set *S*, then its coordinates will change to *(x', y') = (x + delatx, y + deltay)*. Thus, the point *(x' - delatx, y' - deltay)* will always belong to the set *S*. In set algebra, `Translate`

is called isomorph, in other words the set of all translations forms the *translation group T*, which is isomorphic to the space itself. This explains the main logic of the function.

Thus, running the code below in our JavaFX façade:

```
private static double TIMER_INTERVAL = 500;
private double delta = 0;
Timeline translateTimeline = new Timeline(new KeyFrame(Duration.millis(TIMER_INTERVAL),
x -> {
delta = delta <= CANVAS_HEIGHT ? delta + 20 : 0;
draw(gc, translate(disk(new Point(0, -50), 50), 0, delta));
}));
translateTimeline.setCycleCount(Timeline.INDEFINITE);
translateTimeline.play();
```

gives the following façade:

#### Homothety

Let `Scale`

be the function that sends any point *M* to another point *N* such that the segment *SN* is on the same line as *SM*, but scaled by a factor lambda. In algebra of sets, `Scale`

is formulated as follows:

Thus the implementation in Java is as follows:

```
public static Function<Point, Point> scale(double deltax, double deltay, double lambdax, double lambday){
return p -> new Point(lambdax * p.getX() + deltax, lambday * p.getY() + deltay);
}
```

where `(deltax, deltay)`

is the constant vector of the translation and `(lambdax, lambday)`

is the lambda vector.

Let `Scale`

be the function that applies an homothety on a set in the plan. This function is simply implemented as follows in Java:

```
public static Predicate<Point> scale(Predicate<Point> set, double deltax, double deltay,
double lambdax, double lambday){
return x -> set.test(scale(-deltax / lambdax, -deltay / lambday, 1 / lambdax, 1 / lambday).apply(x));
}
```

`Scale`

takes as parameters `deltax`

which is the delta distance in the first Euclidean dimension, `deltay`

which is the delta distance in the second Euclidean dimension and `(lambdax, lambday)`

wich is the constant factor vector lambda. If a point *P (x, y)* is transformed through `ScaleSet`

in a set *S*, then its coordinates will change to *(x', y') = (lambdax * x + delatx, lambday * y + deltay)*. Thus, the point *((x'- delatx)/lambdax, (y' - deltay)/lambday)* will always belong to the set *S*, If lambda is different from the vector 0, of course. In algebra of sets, `ScaleSet`

is called isomorph, in other words the set of all homotheties forms the *Homothety group H*, wich is isomorphic to the space itself \ {0}. This explains the main logic of the function.

Thus, running the code below in our JavaFX façade:

```
private double lambda = 0.05;
Timeline scaleTimeline = new Timeline(new KeyFrame(Duration.millis(TIMER_INTERVAL),
x -> {
delta = delta <= CANVAS_HEIGHT ? delta + 20 : 0;
lambda = delta <= CANVAS_HEIGHT ? lambda + 0.05 : 0.05;
draw(gc, scale(disk(new Point(0, -50), 50), 0, delta, 1, lambda));
}));
scaleTimeline.setCycleCount(Timeline.INDEFINITE);
scaleTimeline.play();
```

gives the following façade:

#### Rotate

Let `Rotation`

be the function that rotates a point with an angle theta. In matrix algebra, `Rotation`

is formulated as follows:

where *(x', y')* are the co-ordinates of the point after rotation, and the formula for *x'* and *y'* is as follows:

The demonstration of this formula is very simple. Have a look at this rotation.

Below the demonstration:

Thus the implementation in Java is as follows:

```
public static Function<Point, Point> rotate(double theta){
return p -> new Point(p.getX() * Math.cos(theta) - p.getY() * Math.sin(theta), p.getX() * Math.sin(theta) + p.getY() * Math.cos(theta));
}
```

Let `Rotate`

be the function that applies a rotation on a set in the plane with the angle theta. This function is simply implemented as follow in Java.

```
public static Predicate<Point> rotate(Predicate<Point> set, double theta){
return p -> set.test(rotate(-theta).apply(p));
}
```

`Rotate`

takes as parameter `theta`

which is the angle of the rotation. If a point *P (x, y)* is transformed through `RotateSet `

in a set *S*, then its coordinates will change to *(x', y') = (x * cos(theta) - y * sin(theta), x * cos(tehta) + y * sin(theta))*. Thus, the point *(x' * cos(tehta) + y' * sin(tehta), x' * cos(theta) - y' * sin(theta))* will always belong to the set *S*. In algebra of sets, `RotateSet`

is called isomorph, in other words the set of all rotations forms the *Rotation group R*, which is isomorphic to the space itself. This explains the main logic of the function.

Thus, running the code below in our JavaFX façade:

```
private double theta = 0;
Timeline rotateTimeline = new Timeline(new KeyFrame(Duration.millis(TIMER_INTERVAL),
x -> {
theta = (theta + Math.PI/2)%(2*Math.PI);
draw(gc, rotate(horizontalHalfPlane(-90, true), theta));
}));
rotateTimeline.setCycleCount(Timeline.INDEFINITE);
rotateTimeline.play();
```

gives the following façade:

### For those who want to go further

Very simple, isn't it? For those who want to go further, you can explore these:

- Ellipse
- Three-dimensional Euclidean space
- Ellipsoide
- Paraboloid
- Hyperboloid
- Spherical harmonics
- Superellipsoid
- Haumea
- Homoeoid
- Focaloid

## Fractals

Fractals are sets that have a fractal dimension that usually exceeds their topological dimension and may fall between the integers. For example, the *Mandelbrot* set is a fractal defined by a family of complex quadratic polynomials:

`Pc(z) = z^2 + c`

where `c`

is a complex. The *Mandelbrot* fractal is defined as the set of all points `c`

such that the above sequence does not escape to infinity. In algebra of sets, this is formulated as follows:

Fractals (abstract data type) can always be represented as follows in Java:

`Function<Complex, Complex> fractal;`

### Complex numbers and drawing

In order to be able to draw fractals, I needed to manipulate complex numbers. Thus, I've created the *Complex* class below.

```
package functional.fractals;
public class Complex {
public static Complex ZERO = new Complex(0, 0);
private double x;
private double y;
public Complex(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double abs(){
return Math.sqrt(this.x * this.x + this.y * this.y);
}
public static Complex add(Complex z1, Complex z2){
return new Complex(z1.getX() + z2.getX(), z1.getY() + z2.getY());
}
public static Complex substract(Complex z1, Complex z2){
return new Complex(z1.getX() - z2.getX(), z1.getY() - z2.getY());
}
public static Complex multiply(Complex z1, Complex z2){
return new Complex(z1.getX() * z2.getX() - z1.getY() * z2.getY(), z1.getX() * z2.getY() + z1.getY() * z2.getX());
}
}
```

I also needed to draw fractals in a `Canvas`

, thus I implemented the `draw`

method below.

```
private static double REAL_MIN = -1.5;
private static double REAL_MAX = 1.5;
private static double IMAGINARY_MIN = -1.5;
private static double IMAGINARY_MAX = 1.5;
private static double BOUNDARY = 1.5;
private static double FRACTAL_ITERATIONS_PERSECOND = 20;
public void draw(GraphicsContext gc, BiFunction<Complex, Complex, Complex> fractal){
for(int x = 0; x < CANVAS_WIDTH; x++){
double xp = REAL_MIN + x * (REAL_MAX - REAL_MIN) / CANVAS_WIDTH;
for(int y = 0; y < CANVAS_HEIGHT; y++) {
double yp = IMAGINARY_MAX - y * (IMAGINARY_MAX - IMAGINARY_MIN) / CANVAS_HEIGHT;
Complex c = new Complex(xp, yp);
Complex z = Complex.ZERO;
for(int k=0; k< FRACTAL_ITERATIONS_PERSECOND;k++) z = fractal.apply(c, z);
if(z.abs() < BOUNDARY) gc.fillRect(x, y, 1, 1);
}
}
}
```

### Mandelbrot Fractal

I've created a Mandelbrot Fractal (abstract data type representation) `P(z) = z^2 + c`

that is available below.

`BiFunction<Complex, Complex, Complex> mandelbrot = (c, z) -> Complex.add(Complex.multiply(z, z), c);`

Thus, running the code below:

`draw(gc, mandelbrot);`

gives the following façade:

### For those who want to go further

For those who want to go further, you can explore these:

- Julia Fractals
- Newton Fractals
- Other Fractals

That's it! I hope you enjoyed reading.