Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eliminate Haskell array bounds check for Bounded type?

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.

like image 931
Norman Ramsey Avatar asked Jul 10 '12 10:07

Norman Ramsey


1 Answers

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.

like image 198
Daniel Fischer Avatar answered Sep 19 '22 11:09

Daniel Fischer