Norman Ramsey
Norman Ramsey

Reputation: 202475

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.

Upvotes: 15

Views: 778

Answers (1)

Daniel Fischer
Daniel Fischer

Reputation: 183873

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.

Upvotes: 14

Related Questions