Re: [Haskell-cafe] Splitting a list

On Wed, 21 Apr 2004 14:57:57 +0100, you wrote:
How about implementing a directly recursive solution? Simply accumulate the sum so far, together with the list elements you have already peeled off. Once the sum plus the next element would exceed the threshold, emit the accumulated elements, and reset the sum to zero.
splitlist threshold xs = split 0 [] xs where split n acc [] = reverse acc: [] split n acc (x:xs) | x >= threshold = error (show x++" exceeds threshold ") | n+x > threshold = reverse acc : split 0 [] (x:xs) | otherwise = split (n+x) (x:acc) xs
Thanks. Apart from a small off-by-one problem (the "x >= threshold" test needs to be "x > threshold" instead), it works fine. I had actually started along those lines, but got bogged down in the details of passing the accumulator around, and ended up painting myself into a corner, so I abandoned that approach (prematurely, as it turns out). And thanks to everyone else who replied--I don't want to clutter the list with a lot of individual replies. As you can probably tell, I've only recently begun playing with Haskell, and the process of reconfiguring my neurons into recursive loops has not yet been completed. -Steve
participants (1)
-
Steve Schafer