Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava function arguments

Tags:

java

guava

Following obviously works, but I do not like to wrap items in Tuple,

    ImmutableMap<String, Function<Tuple2<Double>, Double>> op = new //
    ImmutableMap.Builder<String, Function<Tuple2<Double>, Double>>()
            .put("+", new Function<Tuple2<Double>, Double>() {
                @Override public Double apply(Tuple2<Double> data) {
                    return data.Val_1 + data.Val_2;
                }
            }).build();
    System.out.println(op.get("+").apply(new Tuple2<Double>(3d, 4d)));

I want to write something like:

    ImmutableMap<String, Function<Double[], Double>> op = new //
    ImmutableMap.Builder<String, Function<Double[], Double>>()
            .put("+", new Function<Double[], Double>() {
                @Override
                public Double apply(Double... data) {
                    return data[0] + data[1];
                }
            }).build();
    System.out.println(op.get("+").apply(3d, 4d));

Help would be most useful, ty.

Edit: Problem solved, started using:

public interface T2Function<T> {
    T apply(T Val_1, T Val_2);
}
like image 890
Margus Avatar asked Oct 28 '10 00:10

Margus


1 Answers

I think you'd be better off using an interface of your own, something like this:

public interface Operation {
  double apply(double a, double b);
}

Guava's Function is a single argument function and not really appropriate for anything multi-argument.

Another thing I've experimented with is a ReduceFunction<F, T> that happens to be usable for such a thing. It's for use with the reduce or fold operation and looks something like:

public interface ReduceFunction<F, T> {
  T apply(T a, F b); // I can't decide on good names for the parameters =(
}

This lets you do things like

List<Double> doubles = ...
Double sum = reduce(doubles, MathOps.add(), 0.0);

where MathOps.add() is a ReduceFunction<Double, Double> that does the obvious thing.

like image 50
ColinD Avatar answered Sep 22 '22 15:09

ColinD