tags:

views:

81

answers:

2

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);
}
+2  A: 

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.

ColinD
@CollinD: What is reduce and fold ? I don't get it.
Emil
@Emil: They are functional programming constructs, aka higher-order functions. A `reduce` will generally reduce a list into a single value by combining elements through a supplied function. A `fold` is similar to a reduce operation, except that it can be seeded with an initial value. The function supplied to the `fold` will then combine the list elements and the seeded value.
gpampara
@gpampara: Is such functional programming done using an api ?
Emil
@Emil: Within the Java world, yes. Guava adds some of the foundations for these, making it a very good library to lever. Remember that there are Functional Programming languages that support this out the box - Scala, Lisp, Haskell etc. The addition of closures to Java will make higher-order functions in Java simpler, but looks like we're gonna have to wait for JDK 8 for those.
gpampara