Functional Java Tuples

Just a prototype so far:

https://github.com/claudemartin/FunctionalJavaTuples

The generic types of the arguments are always A, B, C, etc. The result is of generic type R.

It’s my goal to have three forms:

  • Method/Lambda Form: Takes n arguments
  • Curried Form: Methods are chained A -> B -> C -> ... -> R
  • Uncurried Form: Takes a tuple (A,B,C,...) -> R

The idea is to add all the basic functions of Haskell to a project that then uses javatuples.org to have a way of using tuples for functional programming in Java 8.

  • curry / uncurry
  • zip / unzip
  • composition (“.”-operator in Haskell)
  • pipes (“|>” in F#)
  • partial application
  • fn.arity() returns the arity of the function.
  • Convert Suppliers and Consumers to Functions.

There’s still a lot to do…

List of TODOs:

  • Implementations of Fn for Quad ... Decade
  • Unit-Tests (instead of FunctionalDemo.java)
  • Types Curried and Uncurried for such forms of the methods

Contact me on github if you are interested in this project.

Why a Consumer is not a Function.

java.util.function.Consumer does not extend java.util.function.Function. But what if you want a set of both types? Why isn’t there a ConsumerFunction?

A ConsumerFunction is not defined in java.util.function. You can easily do it yourself. But you will see that it’s not that simple. void is a keyword in Java. There is a class Void and (by reflection) you can even get an instance of Void. But you have to use a return statement to get a Function.

Continue reading “Why a Consumer is not a Function.”

LockOnce

Run code only once!

Project hosted on github: https://github.com/claudemartin/LockOnce

It’s just one single utility class to make sure code is run only once. And then there’s another one for easy “Lazy Initialization”.

I once wrote this for Java 7 but now it needs Java 8. It makes much more sense to use this with Lambdas. It’s a bit like the lazy keyword of Scala.

// declaration of lazy field:
final Supplier<Foo> lazy = Lazy.of(() -> ...);
// Access to the data:     
Foo foo = lazy.get();

You can also register a “destructor”. This solves the problem that such fields (they are usually static final) are never GCd and finalizers are utterly useless. In the same way you can have resources (they just have to implement AutoClose) closed on shutdown.