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,y,z] for each (x in range(1,n+1))
[x, for each (y in range(x,n+1)) z]
for each (zx in range(y1, n + 1))
for each(y in if range(x*x, n + y*y == z*z1)) ]
for each(z in range(y, n + 1))
if (x * x + y * y == z * z)
]
}
 
for each (var triple in triples(20))
print(triple);</lang>
 
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)
<code>[(x,y,z) | x <- [1 .. n], y <- [x .. n], z <- [y .. n], x ^ 2 + y ^ 2 == z ^ 2 ]</code>
 
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));
 
// pure :: a -> [a]
const pure = x => [x];
// 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 concatMap(x =>
concatMap(y =>
concatMap(z =>
 
x * x + y * y === z * z ? pure([x, y, z]) : [],
enumFromTo( [x, n))y, z]
enumFromTo(y, n)) ] : [],
 
enumFromTo(x, n)),
enumFromTo(1y, n));,
enumFromTo(x, n)),
enumFromTo(1, n));
})(20);</lang>
{{Out}}
9,659

edits