我正在阅读Norvig 关于 AIP 的书。其中有一个关于编写叉积函数的练习 -
(defun cross-product (fn list-1 list-2)
(mappend #'(lambda (y)
(mapcar #'(lambda (x)
(funcall fn y x))
list-2))
list-1))
(defun mappend (fn the-list)
(if (null the-list)
nil
(append (funcall fn (first the-list))
(mappend fn (rest the-list)))))
我正在尝试用 Java 编写一个实现 -
interface Function<T1, T2, T3> {
public T3 function(T1 t1, T2 t2);
}
public class CrossProduct<T1, T2> {
private List<T1> list1;
private List<T2> list2;
public CrossProduct(List<T1> t1, List<T2> t2) {
this.list1 = t1;
this.list2 = t2;
}
public <T3> List<T3> calculate(Function<T1, T2, T3> fn) {
List product = new ArrayList();
for (int i = 0; i < list1.size(); i++)
for (int j = 0; j < list2.size(); j++)
product.add(fn.function(list1.get(i), list2.get(j)));
return product;
}
}
用法 -
@Test
public void testWithStrings() {
List<String> list1 = new ArrayList<String>();
list1.add("6");
list1.add("8");
List<String> list2 = new ArrayList<String>();
list2.add("2");
list2.add("3");
List<String> product = new CrossProduct<String, String>(list1, list2)
.<String> calculate(new Function<String, String, String>() {
public String function(String x, String y) {
return (String) x + (String) y;
}
});
Assert.assertEquals("62", product.get(0));
Assert.assertEquals("63", product.get(1));
Assert.assertEquals("82", product.get(2));
Assert.assertEquals("83", product.get(3));
}
有没有更好的方法来做到这一点?