List comprehensions: Difference between revisions
→{{header|Haskell}}: ( Adjusted the claim that comprehensions desugar to Do notation - the latter is in fact an alternative sugaring)
m (→JS ES6) |
(→{{header|Haskell}}: ( Adjusted the claim that comprehensions desugar to Do notation - the latter is in fact an alternative sugaring)) |
||
Line 816:
=={{header|Haskell}}==
<lang haskell>pyth
[ (x, y, z)
| x <- [1 .. n]
, y <- [x .. n]
, z <- [y .. n]
, x ^ 2 + y ^ 2 == z ^ 2 ]</lang>
List-comprehensions
The list comprehension above could be re-sugared as:
<lang haskell>import Control.Monad (guard)
pyth ::
pyth n = do
x <- [1..n]
Line 831 ⟶ 836:
guard $ x^2 + y^2 == z^2
return (x,y,z)</lang>
and both of the above could be de-sugared to:
<lang haskell>pyth :: Int -> [(Int, Int, Int)]
pyth n =
[1 .. n] >>=
(\x ->
[x .. n] >>=
(\y ->
[y .. n] >>=
(\z ->
if x ^ 2 + y ^ 2 == z ^ 2
then [(x, y, z)]
else [])))</lang>
which can be further specialised (given the particular context of the list monad, in which >>= is concatMap) to:
<lang haskell>pyth :: Int -> [(Int, Int, Int)]
pyth n =
concatMap
(\x ->
concatMap
(\y ->
concatMap
(\z ->
if x ^ 2 + y ^ 2 == z ^ 2
then [(x, y, z)]
else [])
[y .. n])
[x .. n])
[1 .. n]</lang>
=={{header|Hy}}==
|