I have a list of integers, I need to append elements to it at different times.
let xs =[]::[Int]
usually appending elements to this would be like:
1:xs
but when using IO in a function, it doesn’t seem to work within a do block and gives errors, and
let xs = [1]
let xs=(2:xs)
results in an infinite list like [1,2,2,2,2,…..]
What can I do to correct this?
You seem to have a fundamental misunderstanding about lists in Haskell. The lists are always immutable, so there is no way to add new elements to an existing list. I.e. You can only create new lists.
So, accordingly, the
a:boperator never adds an element to a list, but creates a new list whereais the first element, which is followed by the existing listb.When you say:
You are saying that
xsis a list where the first element is2and the rest of the list isxsitself, which logically results in an infinite list of 2’s. In the context of this question, it’s irrelevant whether you are in the IO monad or not.So given the above, you need to do something like
But of course, this is the same as simply doing
So you really need to give some more context on what kind of list you want to build and why.