[Haskell-cafe] Splitting a list

Henning Thielemann iakd0 at clusterf.urz.uni-halle.de
Wed Apr 21 17:29:50 EDT 2004


On Wed, 21 Apr 2004, Steve Schafer wrote:

> runningSum           ::  (Ord a, Num a) => [a] -> [a]
> runningSum []        =   []
> runningSum (i:[])    =   i : []
> runningSum (i:j:js)  =   i : runningSum (i+j : js)

this is certainly the same as

scanl1 (+)

> zipWithSum           ::  (Ord a, Num a) => [a] -> [(a,a)]
> zipWithSum xs        =   zip (runningSum xs) xs
> 
> threshold            ::  (Ord a, Num a) => [a] -> a -> ([(a,a)],[(a,a)])
> threshold xs t       =   let test x = (t >= (fst x))
>                          in span test (zipWithSum xs)

In general you should make the threshold 't' the first argument of your
functions, since it will have different values less often than 'xs'.

> splitFirst           ::  (Ord a, Num a) => [a] -> a -> ([a],[a])
> splitFirst xs t      =   let (ys,zs) = threshold xs t
>                          in (snd (unzip ys), snd (unzip zs))
> 
> splitAll             ::  (Ord a, Num a) => [a] -> a -> [[a]]
> splitAll [] _        =   []
> splitAll xs t        =   let (ys, zs) = splitFirst xs t
>                          in ys : (splitAll zs t)

With swapped arguments of splitFirst and Maybe value you could invoke it
with 'unfoldr' in splitAll.

Though a recursive algorithm may be more elegant here. 




More information about the Haskell-Cafe mailing list