[prev in list] [next in list] [prev in thread] [next in thread] 

List:       haskell-cafe
Subject:    Re: [Haskell-cafe] Splitting a list
From:       Steve Schafer <steve () fenestra ! com>
Date:       2004-04-23 16:36:12
Message-ID: b4hi80d20ut6hqjmn6u289q3p52odh2r89 () 4ax ! com
[Download RAW message or body]

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

[prev in list] [next in list] [prev in thread] [next in thread] 

Configure | About | News | Add a list | Sponsored by KoreLogic