import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Supplier;
class linkedList {
public T head;
public linkedList tail;
linkedList(T head) { this.head = head; this.tail = null; } linkedList(T head, linkedListtail) { this.head = head; this.tail = tail; }
}
class Main {
public static linkedList cons(T head) {
return new linkedList(head);
}
public staticlinkedList cons(T head, linkedList tail) { return new linkedList (head, tail); } public static String listToString(linkedList list) { if (list == null) { return ""; } if (list.tail == null) { return list.head.toString(); } return list.head.toString() + " " + listToString(list.tail); } public static linkedList myMap(Function fn, linkedList list) { if (list == null) { return null; } return cons(fn.apply(list.head), myMap(fn, list.tail)); } public static T2 myReduce(BiFunction fn, T2 accm, linkedList list) { if (list == null) { return accm; } return myReduce(fn, fn.apply(accm, list.head), list.tail); } public static T2 myReduceRight(BiFunction fn, T2 accm, linkedList list) { // [BEGIN] YOUR CODE HERE return null; // [END] YOUR CODE HERE } public static linkedList myMap2(Function fn, linkedList list) { // [BEGIN] YOUR CODE HERE return null; // [END] YOUR CODE HERE } public static void main(String[] args) { linkedList exampleList = cons(1, cons(2, cons(3, cons(4)))); Function plusOne = (x) -> x + 1; BiFunction xTimesTwoPlusY = (x, y) -> x * 2 + y; BiFunction printXAndReturnY = (x, y) -> { System.out.println(x); return y; }; Function toString = (x) -> x.toString(); BiFunction unfoldCalculation = (x, y) -> "fn(" + x.toString() + ", " + y.toString() + ")"; Function printAndReturn = (x) -> { System.out.println(x); return x; }; System.out.println(listToString(exampleList) + " should be 1 2 3 4"); System.out.println(listToString(myMap(plusOne, exampleList)) + " should be 2 3 4 5"); System.out.println(myReduce(xTimesTwoPlusY, 0, exampleList) + " should be 26"); System.out.println(myReduce(unfoldCalculation, "accm", myMap(toString, exampleList)) + " should be fn(fn(fn(fn(accm, 1), 2), 3), 4)"); System.out.println(myReduceRight(xTimesTwoPlusY, 0, exampleList) + " should be 20"); System.out.println(myReduceRight(unfoldCalculation, "accm", myMap(toString, exampleList)) + " should be fn(1, fn(2, fn(3, fn(4, accm))))"); System.out.println("Below should output 4 3 2 1 each on a separate line:"); myReduceRight(printXAndReturnY, 0, exampleList); System.out.println(listToString(myMap2(plusOne, exampleList)) + " should be 2 3 4 5"); System.out.println("The two outputs below should be equal:"); System.out.println("First output:"); myMap(printAndReturn, exampleList); System.out.println("Second output:"); myMap2(printAndReturn, exampleList); }
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)