Y Combinator in Java 8

The Y Combinator written in Java 8 with nothing but lambdas.

The Y Combinator allows us to use recursion without actually using the recursion that Java already has. And Java 8 actually doesn’t support recursion in lambdas. So this is one way of solving the problem. The simpler one would be to use a recursive Java method and then use a method reference to it (as in MyMathsFunctions::factorial). This is to show that Haskell Curry was right and we can do it with nothing but lambda expressions. Since Java is strongly typed I also need an interface, which references itself in the type declaration. This is necessary because at some point we need to apply a function to itself.

There are enough wiki and blog pages and articles on this. Even videos. So I won’t explain it in details. It’s nothing new, just written in Java 8.

Code on Pastebin

The full Code is here: https://pastebin.com/M2RmRqdU

	private static <T> T apply(UnaryOperator<UnaryOperator<T>> fn, T arg) {
		return ((Function<UnaryOperator<UnaryOperator<T>>, UnaryOperator<T>>)
				a -> ((Fn2Op<T>) b -> b.apply(b))
				.apply(
					c -> a.apply(
						x -> c.apply(c).apply(x)
					)
				)).apply(fn).apply(arg);
	}

Functions in Java

There’s a lot of confusion about “functions” in Java. Java doesn’t really have them, but an object could represent a function so it kind of does have them. I try to explain the different meanings of “functions” in Java, other languages and in mathematics.

Continue reading “Functions in Java”

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.”