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>import Control.Monad (guard)
<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]
guard $ x ^ 2 + y ^ 2 == z ^ 2
if x ^ 2 + y ^ 2 == z ^ 2
return (x, y, z)</lang>
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>import Control.Applicative (empty)
<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 -> pure (x, y, z)
True -> [(x, y, z)]
False -> empty</lang>
_ -> []</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: