[Haskell-cafe] Simple list processing

Andrew Coppin andrewcoppin at btinternet.com
Wed Jun 11 14:17:03 EDT 2008


OK, so this is a fairly basic question about list processing.

Several times now, I have found myself wanting to process a list to 
produce a new list. However, the way later elements are processed 
depends on what the earlier elements are - in other words, this isn't a 
simple "map".

What is the best way to handle this?

According to the theory, anything that consumes a list and produces a 
value is some kind of fold. [Assuming it traverses the list in a 
sensible order!] So it looks like you could implement this as a fold. 
But should that be a LEFT-fold or a RIGHT-fold? (I always get confused 
between the two!)

Actually, anything that takes a value and processes it repeatedly to 
produce a list is technically an unfold. [Again assuming a sensible 
processing order.] So it looks like this function could also be an 
UNfold. As in, you take a list as input, and keep unfolding until that 
list becomes empty.

So it looks like this can be implemented as a fold or an unfold. But 
neither way looks especially easy. Both of these patterns seem to be 
more general than necessary; I only want to take 1 element of input and 
produce 1 element of output, but keeping track of a running state. I 
guess I could use some sort of state monad and make the whole thing 
monadic - but that again is overkill for what I'm trying to do.

Any hints here?



More information about the Haskell-Cafe mailing list