问题
So, I have gotten a bit of an understanding of functional programming but for this I cannot use a loop and instead have to use the foldLeft or foldRight function that I wrote, on order to get the minVal.
static <U,V> V foldLeft(V e, Iterable<U>l, BiFunction<V,U,V> f){
for(U u:l) {
e = f.apply(e, u);
}
return e;
}
static <U,V> V foldRight(V e, Iterable<U>l, BiFunction<U,V,V> f){
for(U u:l) {
e = f.apply(u, e);
}
return e;
I now have to write a minVal:
//(5) Use minVal to calculate the minimum of a List of
// Integers
static <U> U minVal(Iterable<U> l, Comparator<U> c){
// write using fold. No other loops permitted.
List<U> temp = new ArrayList<U>();
l.forEach(temp::add);
return temp.stream().min(c).get(); //Not sure if this actually works yet
}
I have attempted to write this and test it, but I am now stuck also on ow I would test the minVal:
List<Integer> numList = new ArrayList<>();
numList.add(5);
numList.add(10);
numList.add(15);
numList.add(20);
numList.add(22);
numList.add(1);
System.out.println(minVal(numList, 0)); //What would I place as the
//comparable argument
The above, of course, is giving me an error. I have read up on Comparators in Lambda but do not understand how to implement this in the test(or the print statement).
Any help/explanation is appreciated! P.S. Please let me know if I am missing any information, I tried to be as thorough as possible.
回答1:
You can define your minVal
using foldLeft
as :
static <U> U minVal(Iterable<U> l, Comparator<U> c) {
// write using fold. No other loops permitted.
return foldLeft(l.iterator().next(), l, (u, u2) -> c.compare(u, u2) < 0 ? u : u2);
// check for l.iterator().hasNext() or else define the behaviour
}
and then invoke it using the Comparator<Integer
defined as:
List<Integer> numList = List.of(5, 10, 15, 20, 22, 1);
System.out.println(minVal(numList, Integer::compare));
来源:https://stackoverflow.com/questions/59924750/how-would-i-get-the-minval-without-a-loop-and-using-only-foldleft