joel76
joel76

Reputation: 5605

Faster way to create a list

I have to create a list of length n with the value v so I write

let lst = [v | _ <- [1..n]]

Is there a faster way because n may be huge?

Upvotes: 0

Views: 87

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476503

You can work with replicate :: Int -> a -> [a] which might be a bit faster:

let lst = replicate n v

but regardless how large n is, you here do not construct a list. Haskell is lazy, so that means that you it simply will store an "expression" to construct a list. If you are only interested in the second element, then it will not construct the rest of the list.

Note that due to list fusion [ghc-doc], the compiler can sometimes rewrite the expression, such that the list is never constructed, and immediately consumed.

Upvotes: 6

Related Questions