Rgtrg R.

asked • 04/13/20

Given the interface please code the zip function

INTERFACE


import java.util.function.BiFunction;

interface NamedBiFunction extends java.util.function.BiFunction //nested interface that extends from java.util.function.BiFunction

{


String name(); // all classes implementing this interface must have a method called name();

}



public class NamedFunction implements NamedBiFunction {
@Overridepublic String name() {
return null;
}

@Overridepublic Object apply(Object o, Object o2) {
return null;
}

public static void main(String[] args) {
BiFunction<Integer, Integer, Integer> add = (a, b) -> a + b;
System.out.println("Sum = " + add.apply(2, 3));
BiFunction<Integer, Integer, Integer> mul = (a, b) -> a * b;
System.out.println("Multiplication = " + mul.apply(2, 3));
BiFunction<Integer, Integer, Integer> diff = (a, b) -> a - b;
System.out.println("Diffference = " + diff.apply(2, 3));
BiFunction<Integer, Integer, Integer> div = (a, b) ->a/b;
try{
System.out.println("Division = "+div.apply(2,4));
}
catch (ArithmeticException a){
a.printStackTrace();
}


}
}


ZIP FUNCTION TO WRITE


/**

* Applies a given list of bifunctions -- functions that take two arguments of a certain type

* and produce a single instance of that type -- to a list of arguments of that type. The

* functions are applied in an iterative manner, and the result of each function is stored in

* the list in an iterative manner as well, to be used by the next bifunction in the next

* iteration. For example, given

* List<Double> args = Arrays.asList(1d, 1d, 3d, 0d, 4d), and

* List<NamedBiFunction<Double, Double, Double>> bfs = [add, multiply, add, divide],

* <code>zip(args, bfs)</code> will proceed iteratively as follows:

* - index 0: the result of add(1,1) is stored in args[1] to yield args = [1,2,3,0,4]

* - index 1: the result of multiply(2,3) is stored in args[2] to yield args = [1,2,6,0,4]

* - index 2: the result of add(6,0) is stored in args[3] to yield args = [1,2,6,6,4]

* - index 3: the result of divide(6,4) is stored in args[4] to yield args = [1,2,6,6,1]

*

* @param args: the arguments over which <code>bifunctions</code> will be applied.

* @param bifunctions: the list of bifunctions that will be applied on <code>args</code>.

* @param <T>: the type parameter of the arguments (e.g., Integer, Double)

* @return the item in the last index of <code>args</code>, which has the final

* result of all the bifunctions being applied in sequence.

*/

public static <T> T zip(List<T> args, List<NamedBiFunction<T, T, T>> bifunctions);





1 Expert Answer

By:

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.