List comprehensions: Difference between revisions
Content added Content deleted
m (→{{header|Haskell}}: (white space adjustment)) |
(→{{header|Haskell}}: Side-stepped imports in Do notation and desugared code) |
||
Line 822: | Line 822: | ||
List-comprehensions and do notation are two alternative and equivalent forms of syntactic sugar in Haskell. |
List-comprehensions and do notation are two alternative and equivalent forms of syntactic sugar in Haskell. |
||
The list comprehension above could be re-sugared as: |
The list comprehension above could be re-sugared in Do notation as: |
||
<lang haskell> |
<lang haskell>pyth :: Int -> [(Int, Int, Int)] |
||
pyth :: Int -> [(Int, Int, Int)] |
|||
pyth n = do |
pyth n = do |
||
x <- [1 .. n] |
x <- [1 .. n] |
||
y <- [x .. n] |
y <- [x .. n] |
||
z <- [y .. n] |
z <- [y .. n] |
||
if x ^ 2 + y ^ 2 == z ^ 2 |
|||
then [(x, y, z)] |
|||
else []</lang> |
|||
and both of the above could be de-sugared to: |
and both of the above could be de-sugared to: |
||
<lang haskell> |
<lang haskell>pyth :: Int -> [(Int, Int, Int)] |
||
pyth :: Int -> [(Int, Int, Int)] |
|||
pyth n = |
pyth n = |
||
[1 .. n] >>= |
[1 .. n] >>= |
||
Line 846: | Line 843: | ||
\z -> |
\z -> |
||
case x ^ 2 + y ^ 2 == z ^ 2 of |
case x ^ 2 + y ^ 2 == z ^ 2 of |
||
True -> |
True -> [(x, y, z)] |
||
_ -> []</lang> |
|||
which can be further specialised (given the particular context of the list monad, in which (>>=) is flip concatMap, pure is flip (:) [], and empty is []) to: |
which can be further specialised (given the particular context of the list monad, in which (>>=) is flip concatMap, pure is flip (:) [], and empty is []) to: |