0

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?

Micha Wiedenmann
  • 19,979
  • 21
  • 92
  • 137
joel76
  • 5,565
  • 1
  • 18
  • 22
  • 6
    What about `lst = replicate n v`. Note that even if `n` is gigantic, due to laziness, it will not construct the list, unless really necessary. – Willem Van Onsem Nov 12 '19 at 10:38
  • It is for an exercice, the list will be printed – joel76 Nov 12 '19 at 12:43
  • 2
    `replicate` is the proper way however you may also do like `take n $ cycle [v]` – Redu Nov 12 '19 at 13:35
  • What have you done to determine that this is the performance bottleneck? (With 80% confidence: nothing yet, and if you do anything, you will discover it isn't.) – Daniel Wagner Nov 12 '19 at 15:38
  • There were 10 tests, 3 failed because my code was too slow. I'm a newbie in Haskell and I was wondering how to improve the speed of the code. With **replicate**, it was still too slow, The major modification which solve the problem, was to put the result of replicate at the beginning of the list result instead of appending it at the end of the result, and to reverse the final result. – joel76 Nov 12 '19 at 17:43
  • 1
    You could use Difference Lists for efficient appending if you have an append heavy work. https://stackoverflow.com/a/13879693/4543207 – Redu Nov 12 '19 at 18:48
  • Well, I used difference_lists in Prolog, i didn't know their existence in Haskell. Thank you for the link ! – joel76 Nov 12 '19 at 19:20

1 Answers1

6

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.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • 1
    After improving the rest of the code **replicate** help me to solve the exercice !, thank you. – joel76 Nov 12 '19 at 13:31