Proposal: Improve error messages for (!!) (include index and length of list)

Twan van Laarhoven twanvl at gmail.com
Fri Oct 17 11:41:17 UTC 2014


You don't need an extra parameter for calculating the length, because
   len = n - idx
So,

     xs !! (I# n) = go xs n
       where
       go [] idx = error $ "... Index " ++ show (I# n)
               ++ " too large for list of length" ++ show (I# (n -# idx))
       go (x:_) 0# = x
       go (_:xs) idx = go xs (idx +# 1)

By the way, do we still need all the manual unboxing with a modern Ghc?

Twan

On 2014-10-16 14:13, Thomas Schilling wrote:
> Yes, you'd have to calculate the length on the fly. i.e., something
> like this (untested):
>
> xs !! n | n < 0 = error "... negative index ..."
> xs !! (I# n) = go xs n 0#
>    where
>      go [] idx len = error $ "... Index " ++ show (I# (idx +# len) ++ "
> too large for list of length "
>                                    ++ show (I# len)
>      go (x:_) 0# _ = x
>      go (_:xs) idx len = go xs (idx -# 0#) (len +# 1#)
>
> On modern processors the extra addition and the extra parameter
> shouldn't hurt, though we'd need a benchmark to make sure, of course.
> You could also make the error message a bit less helpful and just
> return how far the index pointed past the end of the list.
>
>
> On 16 October 2014 13:46, Herbert Valerio Riedel <hvr at gnu.org> wrote:
>> On 2014-10-16 at 08:20:55 +0200, Simon Hengel wrote:
>>
>> [...]
>>
>>> I propose to change the error messages for the non-report version to
>>> include index and list length, something that is functionally equivalent
>>> to:
>>
>> While I'm very sympathetic to better error messages; doesn't the
>> implementation you gave defer garbage-collecting the start of the list,
>> by keeping the head of the list alive until either the desired index has
>> been reached or end-of-list is detected?
>>
>> e.g. consider something (silly) like ([1..] !! 10000000)
>>
>> Cheers,
>>    hvr
>> _______________________________________________
>> Libraries mailing list
>> Libraries at haskell.org
>> http://www.haskell.org/mailman/listinfo/libraries
> _______________________________________________
> Libraries mailing list
> Libraries at haskell.org
> http://www.haskell.org/mailman/listinfo/libraries
>


More information about the Libraries mailing list