splitAt and negative values

Hello, Could you explain this behaviour?
splitAt (-1) "Foobar" ("","Foobar") splitAt (-100) "Foobar" ("","Foobar")
I don't understand why splitAt (-1) "Foobar" doesn't output this: ("r", "Fooba") or this: ("", "Fooba") How does it work? Python's list slicing looks similar, but results for negative values differ:
a = "Foobar" a[:-1] 'Fooba'
Thanks

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

One problem you might run into is:
a = 4
b = 5
splitAt (a - b) [1..]
If you don't know what a or b are beforehand, you might be opening up a can
of uncomputable worms.
Tom
On Sep 6, 2012 1:25 PM, "Stayvoid"
Hello,
Could you explain this behaviour?
splitAt (-1) "Foobar" ("","Foobar") splitAt (-100) "Foobar" ("","Foobar")
I don't understand why splitAt (-1) "Foobar" doesn't output this: ("r", "Fooba") or this: ("", "Fooba")
How does it work?
Python's list slicing looks similar, but results for negative values differ:
a = "Foobar" a[:-1] 'Fooba'
Thanks
_______________________________________________ Beginners mailing list Beginners@haskell.org http://www.haskell.org/mailman/listinfo/beginners

On Thu, Sep 6, 2012 at 1:24 PM, Stayvoid
splitAt (-1) "Foobar" ("","Foobar")
As others have mentioned, this falls out of the way Haskell implements lists; Perl and Python "lists" are more like Vector, and the end of the list is easier to locate and operate on. It's also worth noting that experience with Perl is that the negative index thing is prone to error (a fencepost error reverses the function's behavior) and Perl 6 has ditched it in favor of a more explicit syntax for the negative index mechanism. -- brandon s allbery allbery.b@gmail.com wandering unix systems administrator (available) (412) 475-9364 vm/sms
participants (5)
-
Brandon Allbery
-
Brent Yorgey
-
Stayvoid
-
Stephen Tetley
-
Tom Murphy