15

I am making a good many arrays whose index type is Bounded and whose index range is (minBound, maxBound). For such an array, a bounds check ought to be unnecessary. How can I persuade GHC to eliminate the bounds check?

My particular application uses both boxed and unboxed immutable arrays, but I am interested in all types of Haskell arrays.

leventov
  • 14,760
  • 11
  • 69
  • 98
Norman Ramsey
  • 198,648
  • 61
  • 360
  • 533

1 Answers1

14

Import Data.Array.Base, compute the Int index of the desired element, and use

someArray `unsafeAt` computedIndex

to avoid the range-check (unsafeRead and unsafeWrite for mutable arrays). The computation of the Int index without range check should be available via unsafeIndex from the Ix class if you import GHC.Arr.

If the Ix instance of your index type doesn't provide a fast unchecked unsafeIndex function, you have to write it yourself. That may be preferable anyway since your range (minBound, maxBound) is constant and needn't be passed to the index computation.

Daniel Fischer
  • 181,706
  • 17
  • 308
  • 431