[Haskell-beginners] list splitting - nice implementation?

Brent Yorgey byorgey at seas.upenn.edu
Sun Nov 18 16:13:15 CET 2012


On Sun, Nov 18, 2012 at 11:53:23AM +0100, Tobias Brandt wrote:
> On 18 November 2012 11:33, Kim-Ee Yeoh <ky3 at atamo.com> wrote:
> 
> > On Sun, Nov 18, 2012 at 4:47 PM, Tobias Brandt <tob.brandt at googlemail.com>
> >  wrote:
> >
> > split xs = getSnds $ span (uncurry (<)) $ zip xs (tail xs)
> >>     where getSnds (as, bs) = (map snd as, map snd bs)
> >>
> >
> > You could prepend negative infinity to not lose the first element.
> >
> >
> 
> Oops, didn't noticed that, nice catch. I'd rather do the following, as it
> works for all types that can be compared with (<), not just for numbers:
> 
> split xs = getSnds $ span (uncurry (<)) $ zip xs (tail xs)
>     where getSnds (as, bs) = (head xs : map snd as, map snd bs)

ghci> split []
([*** Exception: Prelude.head: empty list

Better add a special case for split [].

Incidentally, this is one splitting pattern (splitting based on a
relation between consecutive elements) that the split package [1] does
NOT cover.  I think I have an idea of how to support it but it would
require rewriting a bunch of the internals of the library.

-Brent

[1] http://hackage.haskell.org/package/split



More information about the Beginners mailing list