Implement recursive lambda function using Java 8 - java

Java 8 introduced lambda functions and I want to implement something like factorial:
IntToDoubleFunction fact = x -> x == 0 ? 1 : x * fact.applyAsDouble(x-1);
Compilation returns
error: variable fact might not have been initialized
How can I reference function itself. Class is anonymous but instance exists: It is called fact.

I usually use (once-for-all-functional-interfaces defined) generic helper class which wraps the variable of the functional interface type.
This approach solves the problem with the local variable initialization and allows the code to look more clearly.
In case of this question the code will look as follows:
// Recursive.java
// #param <I> - Functional Interface Type
public class Recursive<I> {
public I func;
}
// Test.java
public double factorial(int n) {
Recursive<IntToDoubleFunction> recursive = new Recursive<>();
recursive.func = x -> (x == 0) ? 1 : x * recursive.func.applyAsDouble(x - 1);
return recursive.func.applyAsDouble(n);
}

One way is to write a secondary function, helper, which takes a function and a number as arguments, and then write the function you actually want, fact = helper(helper,x).
Like so:
BiFunction<BiFunction, Double, Double> factHelper =
(f, x) -> (x == 0) ? 1.0 : x*(double)f.apply(f,x-1);
Function<Double, Double> fact =
x -> factHelper.apply(factHelper, x);
This seems to me to be slightly more elegant than relying on corner case semantics like a closure that captures a reference to a mutable structure, or allowing self-reference with a warning of the possibility of "might not be initialized."
Still, it's not a perfect solution because of Java's type system -- the generics cannot guarantee that f, the argument to factHelper, is of the same type as factHelper (i.e. same input types and output types), since that would be an infinitely nested generic.
Thus, instead, a safer solution might be:
Function<Double, Double> fact = x -> {
BiFunction<BiFunction, Double, Double> factHelper =
(f, d) -> (d == 0) ? 1.0 : d*(double)f.apply(f,d-1);
return factHelper.apply(factHelper, x);
};
The code smell incurred from factHelper's less-than-perfect generic type is now contained (or, dare I say, encapsulated) within the lambda, ensuring that factHelper will never be called unknowingly.

Local and anonymous classes, as well as lambdas, capture local variables by value when they are created. Therefore, it is impossible for them to refer to themselves by capturing a local variable, because the value for pointing to themself does not exist yet at the time they are being created.
Code in local and anonymous classes can still refer to themselves using this. However, this in a lambda does not refer to the lambda; it refers to the this from the outside scope.
You could capture a mutable data structure, like an array, instead:
IntToDoubleFunction[] foo = { null };
foo[0] = x -> { return ( x == 0)?1:x* foo[0].applyAsDouble(x-1);};
though hardly an elegant solution.

If you find yourself needing to do this sort of thing often, another option is to create a helper interface and method:
public static interface Recursable<T, U> {
U apply(T t, Recursable<T, U> r);
}
public static <T, U> Function<T, U> recurse(Recursable<T, U> f) {
return t -> f.apply(t, f);
}
And then write:
Function<Integer, Double> fact = recurse(
(i, f) -> 0 == i ? 1 : i * f.apply(i - 1, f));
(While I did this generically with reference types, you can also make primitive-specific versions).
This borrows from an old trick in The Little Lisper for making unnamed functions.
I'm not sure I'd ever do this in production code, but it is interesting...

Answer is : You have to use a this before name variable calling applyAsDouble function :-
IntToDoubleFunction fact = x -> x == 0 ? 1 : x * this.fact.applyAsDouble(x-1);
if you make the fact final also it will work
final IntToDoubleFunction fact = x -> x == 0 ? 1 : x * this.fact.applyAsDouble(x-1);
We can use functional interface UnaryOperator here. A unary operator that always returns its input argument.
1) Just add this. before the name of the function, as in:
UnaryOperator<Long> fact = x -> x == 0 ? 1 : x * this.fact.apply(x - 1 );
This will hep to avoid “Cannot reference a field before it is defined”.
2) If you prefer a static field, just replace ' this ' with name of the class:
static final UnaryOperator<Long> fact = x -> x== 0? 1: x * MyFactorial.fact.apply(x - 1 );

public class LambdaExperiments {
#FunctionalInterface
public interface RFunction<T, R> extends Function<T, R> {
R recursiveCall(Function<? super T, ? extends R> func, T in);
default R apply(T in) {
return recursiveCall(this, in);
}
}
#FunctionalInterface
public interface RConsumer<T> extends Consumer<T> {
void recursiveCall(Consumer<? super T> func, T in);
default void accept(T in) {
recursiveCall(this, in);
}
}
#FunctionalInterface
public interface RBiConsumer<T, U> extends BiConsumer<T, U> {
void recursiveCall(BiConsumer<T, U> func, T t, U u);
default void accept(T t, U u) {
recursiveCall(this, t, u);
}
}
public static void main(String[] args) {
RFunction<Integer, Integer> fibo = (f, x) -> x > 1 ? f.apply(x - 1) + f.apply(x - 2) : x;
RConsumer<Integer> decreasingPrint = (f, x) -> {
System.out.println(x);
if (x > 0) f.accept(x - 1);
};
System.out.println("Fibonnaci(15):" + fibo.apply(15));
decreasingPrint.accept(5);
}
}
During my tests, this is the best that i could achieve for local recursive lambdas.
They can be used in streams as well but we loose the easyness of the target typing.

One solution is to define this function as an INSTANCE attribute.
import java.util.function.*;
public class Test{
IntToDoubleFunction fact = x -> { return ( x == 0)?1:x* fact.applyAsDouble(x-1);};
public static void main(String[] args) {
Test test = new Test();
test.doIt();
}
public void doIt(){
System.out.println("fact(3)=" + fact.applyAsDouble(3));
}
}

Another version using accumulator so that recursion can be optimised.
Moved to Generic interface definition.
Function<Integer,Double> facts = x -> { return ( x == 0)?1:x* facts.apply(x-1);};
BiFunction<Integer,Double,Double> factAcc= (x,acc) -> { return (x == 0)?acc:factAcc.apply(x- 1,acc*x);};
Function<Integer,Double> fact = x -> factAcc.apply(x,1.0) ;
public static void main(String[] args) {
Test test = new Test();
test.doIt();
}
public void doIt(){
int val=70;
System.out.println("fact(" + val + ")=" + fact.apply(val));
}
}

You can define a recursive lambda as an instance or class variable:
static DoubleUnaryOperator factorial = x -> x == 0 ? 1
: x * factorial.applyAsDouble(x - 1);
for example:
class Test {
static DoubleUnaryOperator factorial = x -> x == 0 ? 1
: x * factorial.applyAsDouble(x - 1));
public static void main(String[] args) {
System.out.println(factorial.applyAsDouble(5));
}
}
prints 120.0.

public class Main {
static class Wrapper {
Function<Integer, Integer> f;
}
public static void main(String[] args) {
final Wrapper w = new Wrapper();
w.f = x -> x == 0 ? 1 : x * w.f.apply(x - 1);
System.out.println(w.f.apply(10));
}
}

A bit like the very first reply ...
public static Function<Integer,Double> factorial;
static {
factorial = n -> {
assert n >= 0;
return (n == 0) ? 1.0 : n * factorial.apply(n - 1);
};
}

The following works but it does seem arcane.
import java.util.function.Function;
class Recursion{
Function<Integer,Integer> factorial_lambda; // The positions of the lambda declaration and initialization must be as is.
public static void main(String[] args) {new Recursion();}
public Recursion() {
factorial_lambda=(i)->{
if(i==1)
return 1;
else
return i*(factorial_lambda.apply(i-1));
};
System.out.println(factorial_lambda.apply(5));
}
}
// Output 120

I heard at the JAX this year, that "lambads do not support recursion". What is meant with this statement is that the "this" inside the lambda always refer to the surrounding class.
But I managed to define - at least how I understand the term "recursion" - a recursive lambda and it goes like that:
interface FacInterface {
int fac(int i);
}
public class Recursion {
static FacInterface f;
public static void main(String[] args)
{
int j = (args.length == 1) ? new Integer(args[0]) : 10;
f = (i) -> { if ( i == 1) return 1;
else return i*f.fac( i-1 ); };
System.out.println( j+ "! = " + f.fac(j));
}
}
Save this inside a file "Recursion.java" and with the two commands "javac Recursion.java" and "java Recursion" it worked for me.
The clou is to keep the interface that the lambda has to implement as a field variable in the surrounding class. The lambda can refer to that field and the field will not be implicitly final.

You can also define it as a local variable by creating a final array of size one (of say Function[]) and then assign the function to element 0. Let me know if you need the exact syntax

Given the fact that "this" in the lambda refers to the containing class, the following compiles with no errors (with added dependencies, of course):
public class MyClass {
Function<Map, CustomStruct> sourceToStruct = source -> {
CustomStruct result;
Object value;
for (String key : source.keySet()) {
value = source.get(key);
if (value instanceof Map) {
value = this.sourceToStruct.apply((Map) value);
}
result.setValue(key, value);
}
return result;
};
}

Another recursive factorial with Java 8
public static int factorial(int i) {
final UnaryOperator<Integer> func = x -> x == 0 ? 1 : x * factorial(x - 1);
return func.apply(i);
}

#IanRobertson Nicely done, in fact you can move the static 'factory' into the body of the interface itself thus encapsulating it entirely:
public static interface Recursable<T, U> {
U apply(T t, Recursable<T, U> r);
public static <T, U> Function<T, U> recurseable(Recursable<T, U> f) {
return t -> f.apply(t, f);
}
}
This is the cleanest solution/answer I have seen so far ... especially since the invocation of "fact" is written "naturally": fac.apply(n) which is what you would expect to see for a unary function like fac()

You can define generic Fixed-point combinator like this.
public static <T, R> Function<T, R> fixedPointCombinator(Function<Function<T, R>, Function<T, R>> f) {
return new Function<T, R>() {
#Override
public R apply(T n) {
return f.apply(this).apply(n);
}
};
}
And
Function<Function<Integer, Double>, Function<Integer, Double>> fact =
self -> n -> n == 0 ? 1 : n * self.apply(n - 1);
System.out.println(fixedPointCombinator(fact).apply(10));
output:
3628800.0

The problem, is that lambda-functions want to operate on final variables, while we need a mutable Function-reference that can be replaced with our lambda.
The easiest trick, appears to be to, to define the variable as a member variable, and the compiler won't complain.
I changed my example to use IntUnaryOperator instead of IntToDoubleFunction, since we're just operating on Integers anyway here.
import org.junit.Test;
import java.util.function.IntUnaryOperator;
import static org.junit.Assert.assertEquals;
public class RecursiveTest {
private IntUnaryOperator operator;
#Test
public void factorialOfFive(){
IntUnaryOperator factorial = factorial();
assertEquals(factorial.applyAsInt(5), 120); // passes
}
public IntUnaryOperator factorial() {
return operator = x -> (x == 0) ? 1 : x * operator.applyAsInt(x - 1);
}
}

Here is a solution that does not rely on a side effect. To make the purpose interesting, let's say that you want to abstract over the recursion (otherwise the instance field solution is perfectly valid).
The trick is to use an anonymous class to get the 'this' reference:
public static IntToLongFunction reduce(int zeroCase, LongBinaryOperator reduce) {
return new Object() {
IntToLongFunction f = x -> x == 0
? zeroCase
: reduce.applyAsLong(x, this.f.applyAsLong(x - 1));
}.f;
}
public static void main(String[] args) {
IntToLongFunction fact = reduce(1, (a, b) -> a * b);
IntToLongFunction sum = reduce(0, (a, b) -> a + b);
System.out.println(fact.applyAsLong(5)); // 120
System.out.println(sum.applyAsLong(5)); // 15
}

You can create a recursive function using this class:
public class Recursive<I> {
private Recursive() {
}
private I i;
public static <I> I of(Function<RecursiveSupplier<I>, I> f) {
Recursive<I> rec = new Recursive<>();
RecursiveSupplier<I> sup = new RecursiveSupplier<>();
rec.i = f.apply(sup);
sup.i = rec.i;
return rec.i;
}
public static class RecursiveSupplier<I> {
private I i;
public I call() {
return i;
}
}
}
And then you can use any functional interface in just 1 line using a lambda and the definition of your functional interface like the following:
Function<Integer, Integer> factorial = Recursive.of(recursive ->
x -> x == 0 ? 1 : x * recursive.call().apply(x - 1));
System.out.println(factorial.apply(5));
I found it very intuitive and easy to use.

Came accross this question during a lecture on Lambdas that used Fibonacci as a possible use case.
You can make a recursive lambda like this:
import java.util.function.Function;
public class Fib {
static Function<Integer, Integer> fib;
public static void main(String[] args) {
fib = (n) -> { return n > 1 ? fib.apply(n-1) + fib.apply(n-2) : n; };
for(int i = 0; i < 10; i++){
System.out.println("fib(" + i + ") = " + fib.apply(i));
}
}
}
What do you have to keep in mind?
Lambdas are evaluated on execution -> they may be recursive
Using a lambda-variable inside of another lambda requires the
variable to be initialized -> before defining a recursive lambda you
must define it with a foo-value
using a local lambda-variable inside a lambda requires the variable
to be final, thus it cannot be redefined -> use a class/ object
variable for the lambda as it is initialized with a default value

Picking up on the common theme of answers here is that lambdas CAN be recursive, providing they have a fixed reference point (hence the class/interface based answers such as #assylias, #Andrey Morozov, #Ian Robertson, etc).
I really liked the answer from #000000000000000000000 with the member variable workaround but I have concerns if the intended lambda function wanted to reference other variables from the containing function's scope. Surely it'll be evaluating those local references at assignment and putting the resulting function into a member variable where it could be accessed by other methods in the class. That doesn't sound ... right (and could get quite interesting if the containing method itself is called recursively).
The following is a variation of the class-based solutions expressed in a form that's close to the OP's original one-line lambda but Eclipse doesn't complain about.
IntToDoubleFunction fact = new IntToDoubleFunction() {
#Override
public double applyAsDouble(int x) {
return x == 0 ? 1 : x * this.applyAsDouble(x-1);
}
};
The { } of course creates an anonymous class and thus a new scope with reference points for the lambda's evaluation with the added benefits of still being within containing function's own scope and thus "sibling" variables.

You could also define interface yourself wher you would just pass it itself as argument during call. E.g
interface MyOwnFunction<T,R>{
R apply(MyOwnFunction<T,R> self,T arg);
}

I don't have a Java8 compiler handy, so can't test my answer. But will it work if you define the 'fact' variable to be final?
final IntToDoubleFunction fact = x -> {
return ( x == 0)?1:x* fact.applyAsDouble(x-1);
};

Related

Java implement accumulator class that provides a Collector

A Collector has three generic types:
public interface Collector<T, A, R>
With A being the mutable accumulation type of the reduction operation (often hidden as an implementation detail).
If I want to create my custom collector, I need to create two classes:
one for the custom accumulation type
one for the custom collector itself
Is there any library function/trick that takes the accumulation type and provides a corresponding Collector?
Simple example
This example is extra simple to illustrate the question, I know I could use reduce for this case, but this is not what I am looking for. Here is a more complex example that sharing here would make the question too long, but it is the same idea.
Let's say I want to collect the sum of a stream and return it as a String.
I can implement my accumulator class:
public static class SumCollector {
Integer value;
public SumCollector(Integer value) {
this.value = value;
}
public static SumCollector supply() {
return new SumCollector(0);
}
public void accumulate(Integer next) {
value += next;
}
public SumCollector combine(SumCollector other) {
return new SumCollector(value + other.value);
}
public String finish(){
return Integer.toString(value);
}
}
And then I can create a Collector from this class:
Collector.of(SumCollector::supply, SumCollector::accumulate, SumCollector::combine, SumCollector::finish);
But it seems strange to me that they all refer to the the other class, I feel that there is a more direct way to do this.
What I could do to keep only one class would be implements Collector<Integer, SumCollector, String> but then every function would be duplicated (supplier() would return SumCollector::supply, etc).
There is no requirement for the functions to be implemented as methods of the container class.
This is how such a sum collector would be typically implemented
public static Collector<Integer, ?, Integer> sum() {
return Collector.of(() -> new int[1],
(a, i) -> a[0] += i,
(a, b) -> { a[0] += b[0]; return a; },
a -> a[0],
Collector.Characteristics.UNORDERED);
}
But, of course, you could also implement it as
public static Collector<Integer, ?, Integer> sum() {
return Collector.of(AtomicInteger::new,
AtomicInteger::addAndGet,
(a, b) -> { a.addAndGet(b.intValue()); return a; },
AtomicInteger::intValue,
Collector.Characteristics.UNORDERED, Collector.Characteristics.CONCURRENT);
}
You first have to find a suitable mutable container type for your collector. If no such type exists, you have to create your own class. The functions can be implemented as a method reference to an existing method or as a lambda expression.
For the more complex example, I don’t know of a suitable existing type for holding an int and a List, but you may get away with a boxed Integer, like this
final Map<String, Integer> map = …
List<String> keys = map.entrySet().stream().collect(keysToMaximum());
public static <K> Collector<Map.Entry<K,Integer>, ?, List<K>> keysToMaximum() {
return Collector.of(
() -> new AbstractMap.SimpleEntry<>(new ArrayList<K>(), Integer.MIN_VALUE),
(current, next) -> {
int max = current.getValue(), value = next.getValue();
if(value >= max) {
if(value > max) {
current.setValue(value);
current.getKey().clear();
}
current.getKey().add(next.getKey());
}
}, (a, b) -> {
int maxA = a.getValue(), maxB = b.getValue();
if(maxA <= maxB) return b;
if(maxA == maxB) a.getKey().addAll(b.getKey());
return a;
},
Map.Entry::getKey
);
}
But you may also create a new dedicated container class as an ad-hoc type, not visible outside the particular collector
public static <K> Collector<Map.Entry<K,Integer>, ?, List<K>> keysToMaximum() {
return Collector.of(() -> new Object() {
int max = Integer.MIN_VALUE;
final List<K> keys = new ArrayList<>();
}, (current, next) -> {
int value = next.getValue();
if(value >= current.max) {
if(value > current.max) {
current.max = value;
current.keys.clear();
}
current.keys.add(next.getKey());
}
}, (a, b) -> {
if(a.max <= b.max) return b;
if(a.max == b.max) a.keys.addAll(b.keys);
return a;
},
a -> a.keys);
}
The takeaway is, you don’t need to create a new, named class to create a Collector.
I want to focus the wording of one point of your question, because I feel like it could be the crux of the underlying confusion.
If I want to create my custom collector, I need to create two classes:
one for the custom accumulation type
one for the custom collector itself
No, you need to create only one class, that of your custom accumulator. You should use the appropriate factory method to instantiate your custom Collector, as you demonstrate yourself in the question.
Perhaps you meant to say that you need to create two instances. And that is also incorrect; you need to create a Collector instance, but to support the general case, many instances of the accumulator can be created (e.g., groupingBy()). Thus, you can't simply instantiate the accumulator yourself, you need to provide its Supplier to the Collector, and delegate to the Collector the ability to instantiate as many instances as required.
Now, think about the overloaded Collectors.of() method you feel is missing, the "more direct way to do this." Clearly, such a method would still require a Supplier, one that would create instances of your custom accumulator. But Stream.collect() needs to interact with your custom accumulator instances, to perform accumulate and combine operations. So the Supplier would have to instantiate something like this Accumulator interface:
public interface Accumulator<T, A extends Accumulator<T, A, R>, R> {
/**
* #param t a value to be folded into this mutable result container
*/
void accumulate(T t);
/**
* #param that another partial result to be merged with this container
* #return the combined results, which may be {#code this}, {#code that}, or a new container
*/
A combine(A that);
/**
* #return the final result of transforming this intermediate accumulator
*/
R finish();
}
With that, it's then straightforward to create Collector instances from an Supplier<Accumulator>:
static <T, A extends Accumulator<T, A, R>, R>
Collector<T, ?, R> of(Supplier<A> supplier, Collector.Characteristics ... characteristics) {
return Collector.of(supplier,
Accumulator::accumulate,
Accumulator::combine,
Accumulator::finish,
characteristics);
}
Then, you'd be able to define your custom Accumulator:
final class Sum implements Accumulator<Integer, Sum, String> {
private int value;
#Override
public void accumulate(Integer next) {
value += next;
}
#Override
public Sum combine(Sum that) {
value += that.value;
return this;
}
#Override
public String finish(){
return Integer.toString(value);
}
}
And use it:
String sum = ints.stream().collect(Accumulator.of(Sum::new, Collector.Characteristics.UNORDERED));
Now… it works, and there's nothing too horrible about it, but is all the Accumulator<A extends Accumulator<A>> mumbo-jumbo "more direct" than this?
final class Sum {
private int value;
private void accumulate(Integer next) {
value += next;
}
private Sum combine(Sum that) {
value += that.value;
return this;
}
#Override
public String toString() {
return Integer.toString(value);
}
static Collector<Integer, ?, String> collector() {
return Collector.of(Sum::new, Sum::accumulate, Sum::combine, Sum::toString, Collector.Characteristics.UNORDERED);
}
}
And really, why have an Accumulator dedicated to collecting to a String? Wouldn't reduction to a custom type be more interesting? Something that along the lines of IntSummaryStatistics that has other useful methods like average() alongside toString()? This approach is a lot more powerful, requires only one (mutable) class (the result type) and can encapsulate all of its mutators as private methods rather than implementing a public interface.
So, you're welcome to use something like Accumulator, but it doesn't really fill a real gap in the core Collector repertoire.
It sounds like you want to supply only the reduction function itself, not all of the other things that come with a generic Collector. Perhaps you're looking for Collectors.reducing.
public static <T> Collector<T,?,T> reducing(T identity, BinaryOperator<T> op)
Then, to sum values, you would write
Collectors.reducing(0, (x, y) -> x + y);
or, in context,
Integer[] myList = new Integer[] { 1, 2, 3, 4 };
var collector = Collectors.reducing(0, (x, y) -> x + y);
System.out.println(Stream.of(myList).collect(collector)); // Prints 10

Implementing functional fold_right in Java

I'm trying to implement the functional method fold_right using some of Java's functional features. The code I have below works, but I don't really understand why it works - I think the main problem is that I'm a little bit uncertain about how lambdas work in Java (especially when using them with generics). For instance, why do I have to call the lambda I return in apply() by calling apply again? The class I'm taking is taught in OCaml, and it's easy for me to understand the fold_right function that OCaml has in its standard library. The way I implemented it in Java just seems so much more clunky and verbose - could someone maybe shed some light on this for me?
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
interface Func<A,B> {
B apply(A a);
}
class Add implements Func<Integer, Func<Integer,Integer>> {
#Override
public Func<Integer,Integer> apply(Integer a) {
return (b) -> a + b;
}
}
public class Fold {
public static <E> E fold(Func<E,Func<E,E>> f, E acc, LinkedList<E> lst) {
if (lst.isEmpty()) {
return acc;
} else {
LinkedList<E> listClone = (LinkedList<E>) lst.clone();
E theHead = listClone.removeFirst();
return (E) f.apply(theHead).apply((fold(f,acc,listClone)));
}
}
public static void main(String[] args) {
Integer[] nums = {1,2,3,4,5};
List<Integer> nums_lst = Arrays.asList(nums);
LinkedList<Integer> lst = new LinkedList<Integer>(nums_lst);
int result = Fold.fold(new Add(), 0, lst);
System.out.println(result); // should be 15
System.out.println(lst); // should be [1,2,3,4,5]
}
}
Slightly off topic, but java has a built in Function<T, R>, that being said, to understand how the code works, let's start with the Func<A, B> interface:
interface Func<A,B> {
B apply(A a);
}
So at a first glance, we have two types namely A, B and the apply method tells me that it takes in an argument of type A and returns an object of type B. Ok moving on to the Add class, this class implements the Func interface as:
Func<Integer, Func<Integer, Integer>>
So based on our previous reasoning, the apply method implemented in Add will take in an Integer and return a Func<Integer, Integer>. So when wee look at the fold method in side the Fold class: (you can think of E as Object for simplicity)
public static <E> E fold(Func<E,Func<E,E>> f, E acc, LinkedList<E> lst) {
if (lst.isEmpty()) {
return acc;
} else {
LinkedList<E> listClone = (LinkedList<E>) lst.clone();
E theHead = listClone.removeFirst();
// A B <- remember the Func interface? here A is E and B is Func<E,E>
// f is a Func<E, Func<E, E>> that takes in an E and returns
// another Func<E, E> after calling apply thus
// breaking the steps:
// f.apply(E) <- we just called the apply method thus this should return a "B"
// Since B is a Func<E, E> we need to call apply to perform the operation
// onto the next element, which in this case is an addition. You can think
// of it as a -> b -> a + b.
// Now you played that nice trick of using recursion to call this function
// and traverse all elements till the end of the collection and accumulate
// all the intermediate results.
return (E) f.apply(theHead).apply((fold(f,acc,listClone)));
// the listClone is one element shorter in each recursion
// since you are removing the first element
}
}
On a side note, since your Func<A, B>, matches the signature of the java.util.Function you can pass the Add as a lambda without implementing the Add class explicilty:
public static void main(String[] args) {
Integer[] nums = {1,2,3,4,5};
List<Integer> nums_lst = Arrays.asList(nums);
LinkedList<Integer> lst = new LinkedList<Integer>(nums_lst);
int result = Fold.fold(a -> b -> a + b, 0, lst);
System.out.println(result); // should be 15
System.out.println(lst); // should be [1,2,3,4,5]
}

Explanation for v-> v>5

I have a given function call and java gives me an error because Objects are not comparable to ints (of course...). Can someone explain to me what I have to change?
I tried to brace the lambda expression differently but with no useful result. I think, that the lambda expression is correct and the filter-function is slightly wrong, but I'm not able to find out my mistake...
// function call
filter(v -> v > 5)
// function
public Optional<T> filter(Predicate<T> tester) {
if(isPresent() && tester.test(get())) {
return this;
} else {
return Optional.empty();
}
}
I would expect a Optional.empty-Object but I get a java-error because v > 5 Object v is not comparable to an int.
You have to make T a wrapper class which is comparable with an int. e.g.
IntStream.range(0, 10)
.filter(v -> v > 5)
.forEach(System.out::println);
is fine because v is an int.
You can't use this expression when T is unknown.
What you can do is assume the T must be a number e.g.
filter( v -> ((Number) v).doubleValue() > 5)
however this will produce a ClassCastExpection is T is another type.
The real solution is to make T a Number
e.g.
class MyClass<T extends Number> {
public Optional<T> filter(Predicate<T> test) {
or make it a specific type like int
class MyClass {
public IntOptional filter(IntPredicate test) {
In Java primitives types (e.g. int) and objects (e.g. Object) don't have a common ancestor in the type hierarchy. Due to that predicates and other stream constructs come in two flavors e.g. there is IntPredicate that you have to use when working with int and Predicate that you have to use when working with Object.
On way to write your filter function would be to use OptionalInt and IntPredicate:
public OptionalInt filter(IntPredicate tester) {
if (isPresent() && tester.test(get())) {
return ...
} else {
return OptionalInt.empty();
}
}
v -> v > 5 can mean different things. It depends on context.
It could be a (Object v) -> v > 5 causing a compilation error since > can't be applied to an Object:
Stream.<Object>of("123", 123).filter(v -> v > 5);
It could be a (Integer v) -> v > 5 meaning that unboxing and autoboxing will be performed in order to do the comparison and to return the result:
Stream.<Integer>of(123, 123).filter(v -> v > 5);
It could be a (int v) -> v > 5 meaning that it's an instance of IntPredicate and things will go smoothly here:
IntStream.of(123, 123).filter(v -> v > 5);
I think, that the lambda expression is correct and the
filter-function is slightly wrong, but I'm not able to find out my
mistake...
You are right.
Your method seems to defeat the generic type declared for the class as first of all your method is defined inside a generic class.
Supposing your class is named Foo, here the filter() method relies on the generic T type as return/parameter type :
public class Foo<T>{
// ...
public Optional<T> filter(Predicate<T> tester) {
// ...
}
}
It works with inference.
So you get Predicate of T. But the T depends on the generic type defined in the class and also from the way which you declared the instance of the Foo class.
And it appears that here T is not a Number.
As alternative you could also rely on inference from the declared Foo variable.
If you do that :
Foo<Integer> foo = new Foo<>();
Optional<Integer> optInt = foo.filter(v -> v > 5);
it will compile fine as Integer will be inferred from Foo<Integer>.
So I think that to solve your issue, you should either declare Number or Integer as base class of the generic type :
public class Foo<T extends Integer>{
// ...
public Optional<T> filter(Predicate<T> tester) {
// ...
}
}
or rely on the inference of the client as in the previous example.

C++11: Class storing a function pointer (templatized, non-member function) to Java

I am not primarily a Java programmer... I would like to find a corresponding Java syntax for class storing a function pointer (templatized) as a variable. The function pointer points to a function "outside" the class. The original code is in C++11:
#include <memory>
template <typename T>
using p_function = T(*)(T, T, T);
template <typename T>
class A
{
private:
int k;
p_function<T> pf;
public:
A() { pf = NULL; k = 0; }
A(p_function<T> pf_, int k_) { pf = pf_; k = k_; }
T getF(const T a1, const T a2, const T a3) const { return pf(a1, a2, a3); }
};
template <typename T>
T f1(T x, T y, T z) { return x + y + z; }
template <typename T>
T f2(T x, T y, T z) { return x - y - z; }
int main()
{
A<double> aa (f1<double>, 1.0);
double val= aa.getF(1.0, 2.0, 3.0);
}
Thinking about the problem, is it reasonable to use the interface?
public interface Function <T> {
T pf(T x, T y, T z);
}
or, is there any better way? Java is relatively rapidly develops, there might be "straighter" constructions than few years ago. There are several requirements which I am not able to join together. Could I ask for a short code sample in Java? Thank you very much for your help.
Use java 8. That uses "functional" interfaces (indeed) where an interface defines just one single function.
To not overuse the existing Function class, introduce your own name.
#FunctionalInterface
public interface TriFunction<T> {
T apply(T x, T y, T z);
}
Marking it with the FunctionalInterface annotation is a practice that prevents adding a second function and such.
class Foo {
public static Bar hop(Bar x, Bar y, Bar z) { ... }
}
TriFunction<Bar> pf = Foo::hop;
TriFunction<Integer> pg = (x, y, z) -> x + y + z;
Bar bara = pf.apply(a, b, c);
For primitive types better define own interfaces without generic parameter types. Above pg needs 3 times to unbox the wrapper objects, and one time to box it again to an object.
The package java.util.function contains many functional interfaces, like BinaryOperator and IntBinaryOperator.
In Java 8, you can use method references. More information here: https://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html
Basically, Java 8 gives interfaces with only one method the special property that they can be used (sort of) like function pointers. You can assign a lambda or a method reference to an object of such a type.
For example, somewhat related to your question:
public class HelloWorld {
public interface Function <T> {
T op(T x, T y);
}
public static class Functions {
static int add(int x, int y) { return x + y; }
static int sub(int x, int y) { return x - y; }
}
static Function<Integer> f1, f2; // <-- "function pointer"
public static void main(String []args) {
f1 = Functions::add; // <-- static method reference
f2 = Functions::sub; // <-- static method reference
System.out.println("Test: " + f1.op(1,2) + ", " + f2.op(1,2));
}
}
This code prints, as you'd expect:
Test: 3, -1
So that part of your question should work. However, the part where you define a generic addition is more problematic, because Java doesn't allow you to overload the operator '+'. So the following will not compile in Java:
T add(T x, T y) {
return x + y; // compile error -> no '+' defined for T
}
If you need T to be base types, you'll need to define your f1 and f2 for each base type you want to use. See also this question: Can I do arithmetic operations on the Number baseclass?
I am not sure if I get your question correctly, but have a look at this stackoverflow post.
There are several answers on how to implement function pointer in java.
EDIT
I am not experienced enough in C++ to provide a code sample.
EDIT 2
According to the post I mentioned above, you could try something like this:
public class WithFunction {
//Empty constructor, can be left out
public WithFunction () {...}
//The function you want to reference
public int myReferencedFunction () {...}
}
Then
public class MethodCaller {
public static Object call (Object theObject, String methodName) {
return theObject.getClass().getMethod(methodName).invoke(theObject);
//catch Exceptions
}
}
Then you can have it like
public static void main (String [] args) {
WithFunction obj1 = new WithFunction();
Object result = MethodCaller.call (obj1, "toString");
int result = (int) MethodCaller.call (obj1, "myReferencedFunction");
}
Notice:
You need to catch a lot of exceptions. Strong error handling needed..
If you use an interface, you can also implement it multiple times and should have the freedom you need

Functional Programming Beginner : Currying in Java

I was reading about currying in functional-programming, and I have a very basic question:
If I have two functions in Java
int add(int x, int y){
return x+y;
}
and I create another method
int increment(int y){
return add(1, y);
}
In the above code, when I wrote increment function, did I actually curry add ?
You have partially applied add. This is related to currying.
In some languages that support partial application, functions are curried by default. you might be able write code like:
increment = add(1)
println(increment(2))
# => 3
A curried function allows you to partially apply that function directly. Java doesn't support that kind of thing without extra machinery.
EDIT:
In Java 8, with lambdas and java.util.function, you can define a curry function.
import java.util.function.Function;
public class Example {
public static <T, U, R> Function<T, Function<U, R>> curry(BiFunction<T, U, R> f) {
return t -> u -> f.apply(t, u);
}
public static int add(int x, int y) {
return x + y;
}
public static void main(String[] args) {
Function<Integer, Function<Integer, Integer>> curriedAdd = curry(Example::add);
// or
// BiFunction<Integer, Integer, Integer> add = (x, y) -> x + y;
// curriedAdd = curry(add);
Function<Integer, Integer> increment = curriedAdd.apply(1);
System.out.println(increment.apply(4));
}
}
EDIT #2:
I was wrong! I've corrected/modified my answer. As sepp2k pointed out this is only partial function application. The two concepts are related and often confused. In my defense there's a section on the currying Wikipedia page about the mixup.
No, you just call it. You need to pass function as argument, and return partial evaluation of that function to call it currying.

Categories