Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Introducing Combinators – Part 1

DZone's Guide to

Introducing Combinators – Part 1

In this article, we present a few basic functional constructs that every developer should be aware of, pertaining specifically to combinators.

· Java Zone ·
Free Resource

Atomist automates your software deliver experience. It's how modern teams deliver modern software.

Outline

In this article, we present a few basic functional constructs that every developer should be aware of. We also introduce the concept of combinator, which is of key importance to write useful functional code, though we carefully avoid digging into the intricacies of combinatory logic.

Background

Have you ever had the need to execute the same code in many places? Have you ever copy-pasted this same code over here and there, because you didn't have time to develop a more robust solution? Or maybe you are a more meticulous programmer and have never done that. Instead, you've created a method with that piece of code and have invoked it from wherever you needed to do it...

As this is a very common problem in software, there already exist many different solutions. Most modern frameworks make use (or abuse) of the proxy pattern and encourage the proliferation of annotations all over business code to intercept target methods and execute common, repetitive code, thus achieving a declarative programming style. If we don't want to annotate a lot of methods with the very same annotation, we can enter the world of AOP (aspect-oriented programming) and define aspects, pointcuts, etc., that will end up executing our piece of code either beforeafter or around the target methods, whether an exception has been thrown or not, etc. There are solutions that even modify our already-compiled bytecode to introduce the corresponding calls to our code... A typical use case is to define transactional methods that are intercepted and, before their execution, a database transaction is started, while after their execution, the transaction is either committed or rolled-back. This way, we don't have to explicitly start and commit/rollback transactions.

In the context of web applications, who hasn't used filters to execute code either before or after the core business code? We can even decide whether to go on with the filter chain or not, based on some precondition, i.e. if the user is logged in and has the proper permissions.

So, while all these tools and approaches help us solve our problem, they have their pros and cons. It is not my goal to analyze them in this article. Instead, I'd like to introduce and discuss a few basic, very useful functional programming techniques that can be used to solve the same kind of problems.

Combinators

Combinators were first introduced on 7 December 1920, when Russian logician and mathematician Moses Schönfinkel delivered a talk to a group of colleagues at the University of Göttingen, Germany. There, he outlined the concept of combinatory logic, which is based on combinators. In late 1927, Haskell Curry rediscovered Schönfinkel's combinators while working at Princeton University, in the USA. Almost a century later, these old-timey, purely theoretical combinators have turned into what we nowadays call a combinator.

Although they've been traditionally put aside by mainstream imperative languages, they have evolved into very powerful functional programming constructs and are indeed quite handy for solving common software problems. The easiest way I know to enter the world of combinators is to first understand what higher-order functions are. As I've mentioned in my first newsletter, I find higher-order functions very useful. This is what I wrote about them there:

The definition of higher-order function I most like states that 'a higher-order function is a function that takes one or more functions as arguments and that might return a function as its result.'

Let's take this definition one step further and use it to introduce the notion of combinator. According to an excerpt from a Wikipedia article, "a combinator is a higher-order function that uses only function application and earlier defined combinators to define a result from its arguments."

Interestingly, the definition is recursive... I must admit that it took me a while to grasp all these concepts. Put into simple words, a combinator is a function that:

  1. Takes one or more functions as arguments.
  2. Might return a function as its result.
  3. Uses only function application and earlier defined combinators on its arguments to produce this result.

So, without further ado, let's dig into some practical, very useful combinators.

Disclaimer: the combinators introduced below are inspired and based on the excellent Method Combinators library written by Reginald 'raganwald' Braithwaite. Please check his page and work for further reference.

Before

Consider the following functional interface:

@FunctionalInterface
public interface Before<T, R>
        extends Function<Consumer<T>,
                Function<Function<T, R>,
                Function<T, R>>> {

    static <T, R> Before<T, R> create() {
        return before -> function -> argument -> {
            before.accept(argument);
            return function.apply(argument);
        };
    }

    static <T, R> Function<T, R> decorate(
            Consumer<T> before, 
            Function<T, R> function) {
        return Before.<T, R>create().apply(before).apply(function);
    }
}

Here the Before interface extends the Function interface, so the first thing to highlight is that Before is a function. Then, analyzing the (quite scary) generic type parameters of the function being extended, we see that Before is actually a currified function that accepts a Consumer<T>  and a Function<T, R> as its arguments and returns a Function<T, R> as its result.

The create factory method returns an instance of the Before functional interface, which is a function that accepts a consumer named before and a function named function as its arguments and returns a function as its result. This result function accepts an argument named argument, which is first passed to the before consumer and then passed to the function function. Finally, the value returned by function is returned.

As only function application is being used within Before's implementation, we can safely affirm that, according to our definition, Before is a combinator (Consumer can be considered as a special kind of function).

The decorate helper method invokes the create factory method and binds the before and function arguments to the returned Before combinator. This process is also called partial function application, and, in this case, it produces a function with the same generic type parameters as the function argument. In other words, we are decorating the function function by means of the Before combinator.

Let's better see an example:

class BeforeExample {

    void demo() {
        System.out.println("----------------------------------");
        System.out.println("Starting BEFORE combinator demo...");
        System.out.println("----------------------------------");

        Function<BigDecimal, String> addTax = this::addTax;

        Consumer<BigDecimal> before = this::before;

        Function<BigDecimal, String> addTaxDecorated =
                Before.decorate(before, addTax);

        BigDecimal argument = new BigDecimal("100");
        String result = addTaxDecorated.apply(argument);

        System.out.println("Done - Result is " + result);
        System.out.println();
    }

    private void before(BigDecimal argument) {
        System.out.println("BEFORE: Argument is " + argument);
    }

    private String addTax(BigDecimal amount) {
        System.out.println("Adding heavy taxes to poor citizen...");
        return "$" + amount.multiply(new BigDecimal("1.22"));
    }
}

This example shows how to use the Before combinator. We first declare the addTax function and the before consumer, which point to the addTax and before methods, respectively. Then we use Before.decorate to create a decorated function, which is the addTaxDecorated function. After executing this decorated function with a value of 100, we get the following output:

----------------------------------
Starting BEFORE combinator demo...
----------------------------------
BEFORE: Argument is 100
Adding heavy taxes to poor citizen...
Done - Result is $122.00

Here we see how the before consumer was executed actually before the addTax function. In fact, this combinator is very useful to execute some code before any given function: just decorate one or more functions with one consumer, and you'll get decorated functions that can be safely used as if they were the original functions.

The typical usage is to log the arguments, but you can do anything you want, with one caveat: if the consumer throws a RuntimeException the original function won't be executed. Throwing an exception from the consumer is not forbidden, but it's discouraged, as this is not the intended use of this combinator. If you want to throw an exception based on some condition on the arguments, you'd better use the Provided combinator, which I'll introduce in the next part of this series about combinators.

After

The After combinator is very similar to the Before combinator. The differences are:

  • The given consumer is executed after the given function.
  • The consumer receives both the argument and the result of the function.

Here's the code:

@FunctionalInterface
public interface After<T, R>
        extends Function<Function<T, R>,
                Function<BiConsumer<T, R>,
                Function<T, R>>> {

    static <T, R> After<T, R> create() {
        return function -> after -> argument -> {
            R result = function.apply(argument);
            after.accept(argument, result);
            return result;
        };
    }

    static <T, R> Function<T, R> decorate(
            Function<T, R> function, 
            BiConsumer<T, R> after) {
        return After.<T, R>create().apply(function).apply(after);
    }
}

Similar considerations as with the Before combinator apply here:

  • The After combinator is also a currified function, though in this case it accepts a  Function<T, R>  and a BiConsumer<T, R> as its arguments.
  • It also returns a Function<T, R> as its result.
  • The create factory method also returns a fresh new instance of the After combinator.
  • The decorate helper method also uses a partial function application to decorate the given function.

The key difference lies in the create method: we first execute the function named function (passing in the argument named argument) and store the result of the execution in the result variable. Then, we pass both argument and result to the after biconsumer. Finally, we return the result variable.

Here's an example:

class AfterExample {

    void demo() {
        System.out.println("---------------------------------");
        System.out.println("Starting AFTER combinator demo...");
        System.out.println("---------------------------------");

        Function<BigDecimal, String> addTaxDecorated =
                After.decorate(this::addTax, this::after);

        String result = addTaxDecorated.apply(new BigDecimal("1000"));

        System.out.println("Done - Result is " + result);
        System.out.println();
    }

    private String addTax(BigDecimal amount) {
        System.out.println("Adding heavy taxes to poor citizen...");
        return "$" + amount.multiply(new BigDecimal("1.22"));
    }

    private void after(BigDecimal argument, String result) {
        System.out.println("AFTER: Argument is " + argument + ", Result is " + result);
    }
}

I've inlined some variables to make the code shorter. Here's the output:

---------------------------------
Starting AFTER combinator demo...
---------------------------------
Adding heavy taxes to poor citizen...
AFTER: Argument was 1000, Result is $1220.00
Done - Result is $1220.00

This output shows that the this::after biconsumer was executed actually after the this::addTax function. This combinator comes in handy for auditing purposes, i.e. if you need to store the arguments and the result of some crucial method's execution, along with any contextual information, such as the date and time, logged user, etc.

Around

The Around combinator is somewhat different to the previous ones. It expects the function to be wrapped and the wrapper itself, which receives a callback to the original function. This callback, when executed, triggers the execution of the actual function. Here's the code:

@FunctionalInterface
public interface Around<T, R>
        extends Function<Function<T, R>,
                Function<BiConsumer<Around.Executable<R>, T>,
                Function<T, R>>> {

    @FunctionalInterface
    interface Executable<R> {
        R execute();
    }

    static <T, R> Around<T, R> create() {
        return function -> around -> argument -> {
            @SuppressWarnings("unchecked")
            R[] result = (R[]) new Object[1];
            Executable<R> callback = () -> result[0] = function.apply(argument);
            around.accept(callback, argument);
            return result[0];
        };
    }

    static <T, R> Function<T, R> decorate(
            Function<T, R> function, 
            BiConsumer<Executable<R>, T> around) {
        return Around.<T, R>create().apply(function).apply(around);
    }
}

Some important considerations:

  • We've defined the Around.Executable functional interface, which will be used as the callback to the actual function we are decorating (we could have used a Supplier instead, whose single abstract method get is equivalent to Around.Executable's execute method, but it didn't feel right to use it as a callback, mainly because it's supposed to be used as a factory).
  • The Around combinator is a currified function that accepts a Function<T, R>> and a BiConsumer<Around.Executable<R>, T> as its arguments and returns a Function<T, R> as its result.
  • The create factory method returns a fresh new instance of the Around combinator.
  • The function function is executed within a callback of type Around.Executable<R>, and this callback is passed as an argument to the around biconsumer.
  • The result of the execution of the function function is stored in an array of one element, because local variables can't be modified within a lambda expression (the elements of an array can be modified, though, which makes the use of this hack a common practice, even in JDK's code, e.g. see the Collectors.boxSupplier private method and its usages).
  • The around biconsumer also accepts the argument of the original function as its second argument.
  • There's no way to modify either the argument or the result of the original function from within the around decorator.
  • If, when implementing the around decorator, the callback of type Around.Executable<R> is never executed, the result of the decorated function will be null
  • The decorate helper method uses partial function application to decorate the given function.

Let's see an example now. Pay attention to the around method, which is our decorator:

class AroundExample {

    void demo() {
        System.out.println("----------------------------------");
        System.out.println("Starting AROUND combinator demo...");
        System.out.println("----------------------------------");

        Function<BigDecimal, String> addTaxDecorated = 
                Around.decorate(this::addTax, this::around);

        String result = addTaxDecorated.apply(new BigDecimal("10000"));

        System.out.println("Done - Result is " + result);
        System.out.println();
    }

    private String addTax(BigDecimal amount) {
        System.out.println("Adding heavy taxes to poor citizen...");
        return "$" + amount.multiply(new BigDecimal("1.22"));
    }

    private void around(Around.Executable<String> function, BigDecimal argument) {
        System.out.println("BEFORE: Amount is " + argument);
        String result = function.execute(); // function executed here!
        System.out.println("AFTER: Result is " + result);
    }
}

I've inlined some variables in this example as well. Here's the output:

----------------------------------
Starting AROUND combinator demo...
----------------------------------
BEFORE: Argument is 10000
Adding heavy taxes to poor citizen...
AFTER: Result is $12200.00
Done - Result is $12200.00

This output shows that the this::addTax function was executed in the middle of the this::around biconsumer, exactly when the function.execute() method was invoked. This is a very useful combinator. You can use it to decorate any function with the code you want, both before and after the function's execution. For example, you could surround the function's execution with a try/catch block and handle any thrown exception as you wish, or you could measure how long it takes to execute the function, or you could even wrap the function's execution within a database transaction, taking care of commit/rollback behavior, etc.

There are other useful combinators I'd like to write about, but I think this article has become long enough by now. In the next part, I will not only introduce them, but also show how combinators can be used together to create complex control flows, while keeping the code clean and readable.

For your convenience, I've created a GitHub repo with all the code shown here. If you want to discuss something or point out some bug you've found, please contact me.

Sign up for the Newsletter

Did you enjoy this post? If so, please consider signing up to The Bounds of Java Newsletter. I plan to write a new post every 2-4 weeks, so if you'd like to be kept in the loop for the next one, I'd really appreciate it if you'd sign up.

Get the open source Atomist Software Delivery Machine and start automating your delivery right there on your own laptop, today!

Topics:
java ,functional programming ,java 8 ,combinators

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}