
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
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@haskell.org http://www.haskell.org/mailman/listinfo/libraries