List comprehensions: Difference between revisions

Content deleted Content added
Hout (talk | contribs)
Hout (talk | contribs)
Line 798: Line 798:




Alternatively, in JavaScript 1.6 onwards, we can emulate the parts of a list comprehension expression by applying '''Array.prototype.filter''' to a functionally defined set, returning a list of matches.
JavaScript 1.6 onwards (while we wait for array comprehension syntax in JavaScript 1.7) we can emulate the parts of a list comprehension expression by applying '''Array.prototype.filter''' to a functionally defined set, returning a list of matches.


Following the pattern of the [[#Mathematica|Mathematica]] example, and using functional set definitions, rather than for loops:
<lang javascript>// Pythagorean filter of triplets drawn from [1 .. n]

function pyth(n) {
return nTuples(range(1, n), 3).filter(
<lang javascript>select(nTuples(range(1, 100), 3), function ([x, y, z]) {
function ([x, y, z]) {
return x * x + y * y === z * z;
});
return x * x + y * y === z * z;
}
)
}


// nTuples(range(20), 3) --> [[1, 2, 3], [1, 2, 4] ... [17, 19, 20], [18, 19, 20]] (1140 tuples)
// nTuples(range(20), 3) --> [[1, 2, 3], [1, 2, 4] ... [17, 19, 20], [18, 19, 20]] (1140 tuples)
Line 835: Line 832:
}
}


function select(lstSet, fnPredicate) {
pyth(20);</lang>
return lstSet.filter(fnPredicate);
}</lang>


Output:
Output:


<pre>[[3, 4, 5], [5, 12, 13], [6, 8, 10], [7, 24, 25], [8, 15, 17], [9, 12, 15], [9, 40, 41], [10, 24, 26], [11, 60, 61], [12, 16, 20], [12, 35, 37], [13, 84, 85], [14, 48, 50], [15, 20, 25], [15, 36, 39], [16, 30, 34], [16, 63, 65], [18, 24, 30], [18, 80, 82], [20, 21, 29], [20, 48, 52], [21, 28, 35], [21, 72, 75], [24, 32, 40], [24, 45, 51], [24, 70, 74], [25, 60, 65], [27, 36, 45], [28, 45, 53], [28, 96, 100], [30, 40, 50], [30, 72, 78], [32, 60, 68], [33, 44, 55], [33, 56, 65], [35, 84, 91], [36, 48, 60], [36, 77, 85], [39, 52, 65], [39, 80, 89], [40, 42, 58], [40, 75, 85], [42, 56, 70], [45, 60, 75], [48, 55, 73], [48, 64, 80], [51, 68, 85], [54, 72, 90], [57, 76, 95], [60, 63, 87], [60, 80, 100], [65, 72, 97]]</pre>
<pre>[[3, 4, 5], [5, 12, 13], [6, 8, 10], [8, 15, 17], [9, 12, 15], [12, 16, 20]]</pre>


=={{header|jq}}==
=={{header|jq}}==