[Haskell-beginners] splitAt and negative values

Brent Yorgey byorgey at seas.upenn.edu
Thu Sep 6 23:12:47 CEST 2012


On Thu, Sep 06, 2012 at 09:24:13PM +0400, Stayvoid wrote:
> Hello,
> 
> Could you explain this behaviour?
> 
> > splitAt (-1) "Foobar"
> ("","Foobar")
> > splitAt (-100) "Foobar"
> ("","Foobar")

That is simply how splitAt is defined.  It treats negative values as
if they were 0.

If you are looking for an explanation of *why* this behavior was
chosen, it is probably because Haskell lists are really *singly-linked
lists*, not arrays.  Taking something off the end of a list takes O(n)
time and requires making a copy of the entire list.  So it wouldn't be
a good idea to encourage it.

If you really need this sort of functionality often then perhaps you
should be using a different type, such as Data.Text, which has
functions for doing things efficiently at the end of some text:

  http://hackage.haskell.org/package/text

-Brent



More information about the Beginners mailing list