List comprehensions: Difference between revisions
→ES6: Dropped the 'pure' function, for a simpler [] literal. Applied formatter
(→{{header|Haskell}}: Side-stepped imports in Do notation and desugared code) |
(→ES6: Dropped the 'pure' function, for a simpler [] literal. Applied formatter) |
||
Line 1,011:
<lang javascript>function range(begin, end) {
for (let i = begin; i < end; ++i)
yield i;
}
function triples(n) {
return [
[x,
for each(y in
for each(z in range(y, n + 1))
if (x * x + y * y == z * z)
]▼
}
for each
outputs:
Line 1,036 ⟶ 1,039:
List comprehension notation was not, in the end, included in the final ES6 standard, and the code above will not run in fully ES6-compliant browsers or interpreters, but we can still go straight to the underlying monadic logic of list comprehensions and obtain:
<code>[ (x, y, z)
by using <code>concatMap</code> (the monadic bind function for lists), and <code>x => [x]</code> (monadic pure/return for lists):
Line 1,042 ⟶ 1,046:
<lang JavaScript>(n => {
'use strict';
// GENERIC FUNCTIONS ------------------------------------------------------
// concatMap :: (a -> [b]) -> [a] -> [b]
const concatMap = (f, xs) => [].concat.apply([], xs.map(f));
// enumFromTo :: Int -> Int -> [Int]
const enumFromTo = (m, n) =>
Line 1,056 ⟶ 1,057:
length: Math.floor(n - m) + 1
}, (_, i) => m + i);
// EXAMPLE ----------------------------------------------------------------
// [(x, y, z) | x <- [1..n], y <- [x..n], z <- [y..n], x ^ 2 + y ^ 2 == z ^ 2]
return
x * x + y * y === z * z ?
▲ enumFromTo(x, n)),
enumFromTo(x, n)),
enumFromTo(1, n));
})(20);</lang>
{{Out}}
|