While loops in a functional way

Written by Mauro Rocchi on 24 March 2015

The following code shows a technique to implement while loops taking advantage of java streams and functional programming.

Do/while loops

This is a classic do/while loop where the body is essentially a supplier of states:

T state;
do {
    state = body();
} while (predicate(state));

It is equivalent to the following code:

final T endState = Stream.generate(body)

The stream will terminate when the current generated value hold the predicate in the filter clause, therefore such clause - used in this way - behaves as an "until" condition and must be negated.

The stream is consumed invoking findFirst, at that point can happend two things:

  1. the stream terminates: findFirst returns an Optional containing the last state checked by the predicate, so the last state is always available;
  2. the stream doesn't terminate: unfortunately there's an infinite loop!

Stateful while loops

Sometimes the current state of a while loop depends from the previous state:

T state = initial;
while (predicate(state)) {
    state = body(state);

The equivalent functional code is similar to the previous but it uses iterate to generate a chain of dependent states:

final T endState = Stream.iterate(initial, body)

Playing with Haskell

Written by Mauro Rocchi on 15 April 2013

Have you ever written a program to calculate the symbolic derivative for a given function? I've tried to solve this problem with Haskell and the result is very simple and smart.

First at all, let's define the data structures representing the math terms:

data Term = Const Integer | Variable String |
            Add Term Term | Mul Term Term |
            Div Term Term | Pow Term Term |
            Sin Term | Cos Term | Tan Term | Ln Term

Assuming to have the functions add x y, mul x y, etc., we can define the derivative functions implementing the math rules:

derive (Variable u) (Variable v) = Const (if u == v then 1 else 0)
derive (Const _) _ = zero
derive (Add x y) v = add (derive x v) (derive y v)
derive (Mul x y) v = add (mul (derive x v) y) (mul x (derive y v))
derive (Pow x y) v = mul (mul y (pow x (sub y one))) (derive x v)
derive (Div x y) v = divide (sub (mul (derive x v) y) (mul x (derive y v))) (pow y two)
derive (Sin x)   v = mul (cos x) (derive x v)
derive (Cos x)   v = mul (neg (sin x)) (derive x v)
derive (Tan x)   v = derive (Div (sin x) (cos x)) v
derive (Ln x)    v = mul (inv x) (derive x v)

Monitoring logs with Sauron

Written by Mauro Rocchi on 13 February 2013

Sauron is a simple self-contained Python 2.3 script, without any dependency, useful to monitor errors on log files in real time from the command-line.

By default it follows all log files in /var/log directory and shown the rows containing an "error" word (bad, cannot, error, exception, fail, fails, failed, failure, incorrect, invalid, unable, unexpected, wrong).

$ sauron [options] [paths (default /var/log)]

    -h, --help            show this help message and exit
                          filename regex (default 'log$')
    -a, --all             the log file are followed from the begin
    -w WORDS, --words=WORDS
                          comma-separed words which filters the lines (default:
                          error, exception, fail, fails, failed, failure,
                          cannot, unable, unexpected, incorrect, invalid, bad,
    -r LINE_REGEX, --regex=LINE_REGEX
                          regex to filter the log lines (it overwrites the
                          --words option)
                          interval in seconds before to scan again the paths
                          (default 1)

The N-queens problem

Written by Mauro Rocchi on 23 January 2013

The problem of the N-queens is a classic puzzle that consists in placing N queens on a chessboard NxN without that they threaten each other. With languages ‚Äč‚Äčthat natively support the functional constructs, like Scala, the problem can be solved with less than 10 lines of code (without loss of clarity), with Java of course it's a bit more tricky. I propose the classic backtracking algorithm, developed with a functional object-oriented approach, using Emaze Dysfunctional extensively.

public static List<List<Integer>> queens(int n) {
    final List<Pair<Integer, Integer>> queenMoves = Arrays.asList(
            Pair.of(-1, -1),
            Pair.of(-1, 0),
            Pair.of(-1, 1));
    final Mover mover = new Mover(queenMoves);
    final IsQueenSafe isQueenSafe = new IsQueenSafe(mover);
    final PlaceNextQueens placeNextQueens = new PlaceNextQueens(isQueenSafe);
    final Iterable<Integer> columns = new Ranges(new ComparableComparator<Integer>(), new NextIntegerSequencingPolicy(), 0).rightHalfOpen(0, Maybe.just(n));
    return new PlaceQueens(Dispatching.curry(placeNextQueens, columns)).perform(n);

Introduction to Emaze Dysfunctional

Written by Mauro Rocchi on 22 January 2013

Emaze Dysfunctional is a Java library providing the support for the functional programming, released by Emaze Networks under BSD license. Developed in accordance with solid principles of OOP, it's distinguished from other similar libraries for simplicity, robustness and high reusability of its components.

I will describe the main features of the current version 5.2 through some demonstrative examples, taken from the "classical" literature.


The following fragment implements the quicksort algorithm, choosing, for simplicity, the first item as the pivot.

static <T> Iterator<T> quicksort(Iterator<T> items, BinaryPredicate<T, T> order) {
    if (!items.hasNext()) {
        return items;
    final T head = items.next();
    final List<T> tail = Consumers.all(items);
    return Multiplexing.chain(
            quicksort(Filtering.filter(tail, Dispatching.rcurry(order, head)), order),
            quicksort(Filtering.filter(tail, Logic.not(Dispatching.rcurry(order, head))), order));

The function, in addition to the iterator with the items to sort, takes an argument of type BinaryPredicate, one of several functors provided by the library. It belong to the predicates family, that is those functions that return a boolean value. The "binary" prefix means that it's a predicate with ariety 2, infact it receives two values and retorns true if these are in order.

The available functors, intended to become your best friends, in order of arity (from 0 to 3) are:

As you can see a QuadruplePredicate doesn't exist, indeed Dysfunctional is developed following the one, two, three, too many! principle. If you need a fourth parameter, probably, or there are some design errors, or it could be the case of grouping related parameters into a container object.