Note that there are some explanatory texts on larger screens.

plurals
  1. POCross-product calculator in Java
    primarykey
    data
    text
    <p>I am working my way through <a href="http://rads.stackoverflow.com/amzn/click/1558601910" rel="nofollow">Norvig's book on AIP</a>. There is an exercise in it on writing a cross-product function -</p> <pre><code>(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))))) </code></pre> <p>I am trying to write an implementation in Java - </p> <pre><code>interface Function&lt;T1, T2, T3&gt; { public T3 function(T1 t1, T2 t2); } public class CrossProduct&lt;T1, T2&gt; { private List&lt;T1&gt; list1; private List&lt;T2&gt; list2; public CrossProduct(List&lt;T1&gt; t1, List&lt;T2&gt; t2) { this.list1 = t1; this.list2 = t2; } public &lt;T3&gt; List&lt;T3&gt; calculate(Function&lt;T1, T2, T3&gt; fn) { List product = new ArrayList(); for (int i = 0; i &lt; list1.size(); i++) for (int j = 0; j &lt; list2.size(); j++) product.add(fn.function(list1.get(i), list2.get(j))); return product; } </code></pre> <p>}</p> <p>Usage -</p> <pre><code>@Test public void testWithStrings() { List&lt;String&gt; list1 = new ArrayList&lt;String&gt;(); list1.add("6"); list1.add("8"); List&lt;String&gt; list2 = new ArrayList&lt;String&gt;(); list2.add("2"); list2.add("3"); List&lt;String&gt; product = new CrossProduct&lt;String, String&gt;(list1, list2) .&lt;String&gt; calculate(new Function&lt;String, String, String&gt;() { 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)); } </code></pre> <p>Is there a better way of doing this?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload