List comprehensions: Difference between revisions

→‎{{header|Haskell}}: ( Adjusted the claim that comprehensions desugar to Do notation - the latter is in fact an alternative sugaring)
(→‎{{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 :: (Enum t, Eq t, Num t)n => t -> [(t, t, t)]
[ (x, y, z)
pyth n = [(x,y,z) | x <- [1..n], y <- [x..n], z <- [y..n], x^2 + y^2 == z^2]
| x <- [1 .. n]
</lang>
, y <- [x .. n]
, z <- [y .. n]
, x ^ 2 + y ^ 2 == z ^ 2 ]</lang>
 
List-comprehensions inand Haskelldo notation are intwo factalternative syntacticand sugarequivalent forforms do-notation,of sosyntactic thesugar abovein is equivalent to the following:Haskell.
 
The list comprehension above could be re-sugared as:
 
<lang haskell>import Control.Monad (guard)
 
pyth :: (Enum t, Eq t, Num t) => tInt -> [(tInt, tInt, tInt)]
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}}==
9,659

edits