[Haskell-cafe] Re: Query on list comprehension

Jon Fairbairn jon.fairbairn at cl.cam.ac.uk
Wed Mar 18 06:07:49 EDT 2009


Melanie_Green <jac_legend_sas at hotmail.com> writes:

> What are the limitations of list comprehension. I want to use
> listcomprehension to output the pattern below. So a mixture of a's and
> newline characters. The part im stuck at is creating arguments in the
> listcomprehension to stop at some point then execute next loop. Is it even
> possible to create the pattern below purely from list comprehension.Thankyou
> in advance. 
>
> a
> aa
> aaa

I'm not clear what you mean by the question. Why do you want
to use list comprehensions? What if they aren't the best way
of getting the result you want?

You can write 

[a | b <- [replicate n 'a' | n <- [1..]], a <- b ++ "\n"] 

but does that "replicate" fail to meet your specification?
If not, you can replace it with another list comprehension
like this:

[a | b <- [['a'| m <- [1..n]] | n <- [1..]], a <- b ++ "\n"]

but at this point, comprehension is not what most people
would get from reading the code. I'd say it was clearer to
write

concat [replicate n 'a' ++ "\n" | n <- [1..]]





-- 
Jón Fairbairn                                 Jon.Fairbairn at cl.cam.ac.uk
http://www.chaos.org.uk/~jf/Stuff-I-dont-want.html  (updated 2009-01-31)



More information about the Haskell-Cafe mailing list