My English is not good. So I try to explain my question in code. Please try to answer me in code. It makes me understand easily.
I have a question: In C++,we can realize that like these codes.
int max(int x,int y)
{
return (x>y)?x:y;
}
float max(float x,float y)
{
return (x>y)?x:y;
}
I can do this to expand code
template <class T>
T max(T x, T y)
{
return (x>y)?x:y;
}
How can I realize the similar function in Java.
You can use generics. Because generics do not work with primitives, and objects cannot be compared with greater-than and less-than operators, we must instead restrict the input types to Comparables (things which can be compared) so that we can use the compareTo method instead:
public static <T extends Comparable<T>> T max(T first, T second)
{
return first.compareTo(second) >= 0 ? first : second;
}
Sample usage:
max(1, 2)
will autobox the primitives to Integers (which do implement Comparable<Integer>) and return 2.
The underlying assumption in the c++ code is that the T type supports the > operator. Java doesn't have operator overloading, but the equivalent would be to limit the code to Ts that implement the Comparable interface:
public static <T extends Comparable<T>> T max(T x, T y)
{
if (x.compareTo(y) > 0) {
return x;
}
return y;
}
Or, alternatively, allow the caller to pass a custom Comparator:
public static <T> T max(T x, T y, Comparator<T> cmp)
{
if (cmp.compare(x, y) > 0) {
return x;
}
return y;
}
Use generics. They are like templates but work in runtime
package test;
class BoxPrinter<T> {
private T val;
public BoxPrinter(T arg) {
val = arg;
}
public String toString() {
return "{" + val + "}";
}
public T getValue() {
return val;
}
}
https://www.geeksforgeeks.org/generics-in-java/
More examples here
So... not entirely sure if this has been answered before, though I suspect it has and I simply didn't understand it with my current knowledge of the language. As such, a tad bit further of an explanation may be nice, the thread I believe that this may be a duplicate of is
Java Pass Method as Parameter
The basic idea of what I would like to do is something like this:
public void doStuff(String parameter, int parameter, Action/Method/Scope/thing action){
for(parameters){
action();
}
}
which would be called like this:
String parameter1;
int parameter2;
doStuff(parameter1, parameter2){
action
}
this is really generic. Sorry about not having anything specific now. The main thing I'm thinking of is that I've been trying to make an "artillery game" similar to Arcanists (target), or maybe gravitee wars (as a more recent/popular example) the annoying bit is I am frequently working with editing images at a pixel level because the generic bufferedImage/graphic/whatever the normal one & GreenfootImage (greenfoot is the environment I'm using) lack what I want.
really tired right now, please be patient with me. if some of this looks odd of incoherent feel free to ask for clarification, I'm not always the easiest to understand when I'm typing tiredly.
To "pass a method" in Java 8, you need a matching functional interface, i.e. an interface with only one method, whose parameters and return type matches the method you want to pass.
You can use one of the standard methods in the java.util.function package, or you can write your own. E.g. the standard interfaces has various methods with 0, 1, or 2 parameters.
Since your parameters are different type, you can use BiFunction, or you could create your own like this:
public interface StringIntConsumer {
void accept(String s, int i);
}
You can now write code to accept such a method:
public void doStuff(String text, int count, StringIntConsumer action) {
for (int i = 0; i < count; i++) {
action.accept(text, i);
}
}
Then call it using a Lambda Expression:
doStuff("Foo", 10, (name, idx) -> {
// use name and idx here
// will be called 10 times with idx value 0-9
});
As you can see, the parameter names don't need to match.
You have described a BiFunction<T, U, R>,
static <T, U, R> R doStuff(T t, U u, BiFunction<T, U, R> func) {
return func.apply(t, u);
}
And you might call it like
public static void main(String[] args) {
System.out.println(doStuff("Hello", 1, (x, y) -> x + " " + y));
}
which just prints "Hello 1" - but it wasn't clear what action you wanted to do.
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
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);
};