Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type safety for size vs index #65

Closed
lehins opened this issue Dec 11, 2018 · 0 comments
Closed

Type safety for size vs index #65

lehins opened this issue Dec 11, 2018 · 0 comments
Assignees
Projects
Milestone

Comments

@lehins
Copy link
Owner

lehins commented Dec 11, 2018

Currently it is way too easy to mix up index with size, since they are of the same type. For example function isSafeIndex :: ix -> ix -> Bool does not give any type level guarantees that first argument is size while the second one is index, which can lead to nasty bugs.

This ticket proposes a newtype wrapper:

newtype Sz ix = Sz ix

Which will not have any runtime overhead but will promote library safety.

This change will affect many functions in the library, for example core function makeArray will now have a type signature:

makeArray :: Construct r ix e => Comp -> Sz ix -> (ix -> e) -> Array r ix e

but the change, IMHO, totally worth it. Especially since transitioning current code is trivial.

Together with the wrapper should be added helper pattern synonyms:

pattern Sz1 :: Int -> Sz Ix1
pattern Sz1 i = Sz i

pattern Sz2 :: Int -> Int -> Sz Ix2
pattern Sz2 m n = Sz (m :. n)

...
-- so forth until Sz5

Bonus.

It would be possible to prevent negative size to be constructed altogether similar to how the Stride is currently implemented. Unlikely that it will have any overhead, but the drawback is that on ghc < 8.2 pattern matching will be yielding an non-exhaustive warning. That is still up for a debate though. Moreover it can be added in the future, since it would be backwards compatibe.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
massiv
  
Awaiting triage
Development

No branches or pull requests

1 participant