(!!) with an overflow integer

I recently started studying Haskell and started playing with the idea of ​​endless lists and lazy pricing. I built an endless list and tried to access an element in a very very remote index using an operator !!. The problem is that the type signature for the operator is as !!follows:

(!!) :: [a] -> Int -> a

This means that to get this item from the list is required Intas an index.

Now my problem arises when I try to index something so far that it overflows Intand therefore becomes negative. What then would be the right way for Haskell to do this?

+4
source share
2 answers

Data.List.genericIndex , Integer, .

+8

!! Integer Int:

(!!!) :: [a] -> Integer -> a
xs     !!! n | n < 0 =  error "negative index"
[]     !!! _         =  error "index too large"
(x:_)  !!! 0         =  x
(_:xs) !!! n         =  xs !!! (pred n)
+1

Source: https://habr.com/ru/post/1524188/


All Articles