How to do stateful list operations in haskell

Viewed 1133

I need an operation which iterates over a list and produces a new list, where the new list elements depend on all elements previously seen. To do this I would like to pass an accumulator/state from iteration to iteration.

Think for example of a list of tuples, where the components of a tuple can be "undefined". An undefined value shall assume the latest value of the same component earlier in the list, if any. So at any stage I will have a state of defined components, which I need to pass to the next iteration.

So with a list of type [l] and an accumulator/state of type a there will be a function of type

f :: a -> l -> (a,l)

i.e it spits out a new list element and a new accumulator.

Is there a function which allows simply applying f to a list? I looked at fold, scan and unfold, but none of them seem to do the trick.

Edit: While the state monad looks promising, I can only see how I would get the final state, but I fail to see how I would get the new list elements.

3 Answers
Related