List comprehensions: Difference between revisions

Content added Content deleted
(Added Java implementation)
Line 1: Line 1:
{{task|Basic language learning}}
{{task|Basic language learning}}
{{Omit From|Java}}
{{Omit From|Modula-3}}
{{Omit From|Modula-3}}
{{omit from|ACL2}}
{{omit from|ACL2}}
Line 952: Line 951:
9 12 15
9 12 15
12 16 20</lang>
12 16 20</lang>

=={{header|Java}}==
Java can stream a list, allowing something like a list comprehension. The syntax is (unsurprisingly) verbose, so you might wonder how good the likeness is. I've labeled the parts according to the description in Wikipedia.

Using list-of-arrays made the syntax easier than list-of-lists, but meant that you need the "output expression" part to get to something easily printable.
<lang Java>// Boilerplate
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class PythagComp{
public static void main(String[] args){
System.out.println(run(20));
}

static List<List<Integer>> run(int n){
return

// Here comes the list comprehension bit

// input list - bit clunky
new ArrayList<Integer[]>(){{
for(int x=1; x<n; x++)
for(int y=x; y<n; y++)
for(int z=y; z<n; z++)
add(new Integer[]{x,y,z});
}}.stream()

// predicate
.filter(a -> a[0]*a[0] + a[1]*a[1] == a[2]*a[2])

// output expression
.map(a -> Arrays.asList(a))

// the result is a list
.collect(Collectors.toList());
}
}
</lang>
{{Out}}
<pre>[[3, 4, 5], [5, 12, 13], [6, 8, 10], [8, 15, 17], [9, 12, 15]]</pre>


=={{header|JavaScript}}==
=={{header|JavaScript}}==