Jump to content

List comprehensions: Difference between revisions

→‎{{header|Haskell}}: Side-stepped imports in Do notation and desugared code
m (→‎{{header|Haskell}}: (white space adjustment))
(→‎{{header|Haskell}}: Side-stepped imports in Do notation and desugared code)
Line 822:
List-comprehensions and do notation are two alternative and equivalent forms of syntactic sugar in Haskell.
 
The list comprehension above could be re-sugared in Do notation as:
 
<lang haskell>importpyth Control.Monad:: Int -> [(guardInt, Int, Int)]
 
pyth :: Int -> [(Int, Int, Int)]
pyth n = do
x <- [1 .. n]
y <- [x .. n]
z <- [y .. n]
guard $if x ^ 2 + y ^ 2 == z ^ 2
returnthen [(x, y, z)</lang>]
else []</lang>
 
and both of the above could be de-sugared to:
<lang haskell>importpyth Control.Applicative:: Int -> [(emptyInt, Int, Int)]
 
pyth :: Int -> [(Int, Int, Int)]
pyth n =
[1 .. n] >>=
Line 846 ⟶ 843:
\z ->
case x ^ 2 + y ^ 2 == z ^ 2 of
True -> pure [(x, y, z)]
False_ -> empty[]</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:
9,659

edits

Cookies help us deliver our services. By using our services, you agree to our use of cookies.