sdiehl / galois-field

Finite field and algebraic extension field arithmetic
MIT License
50 stars 13 forks source link

Avoid unsafeCoerce in prime fields #29

Closed Bodigrim closed 4 years ago

Bodigrim commented 4 years ago

Instead of defining newtype Prime (p :: Nat) = P Natural and unsafe-coercing between it and Mod p, one can define Prime to be a newtype wrapper over Mod and avoid unsafeCoerce. It also allows to inherit many instances from Mod by means of GND.

I removed instance Bits (Prime p), since bit fiddling with modular values is obviously highly unsafe. This instance is not used anywhere in the library and other types of fields do not define it, so I hope this is fine.

I also removed toP', which is nothing else but a legitimized unsafeCoerce. It does not really look appropriate for this library to depend on the internal representation of Data.Mod. If an end user is so brave and so desperate, that safe toP is not enough, he can probably reach out for unsafeCoerce directly.

sdiehl commented 4 years ago

I believe there was some performance reason this was originally introduced instead of GND because of some subtle inliner optimisation not firing. I'll double check and see if the benchmarks seem fine, then I'll merge this. Would definitely prefer less unsafeCoerce whenever possible.

sdiehl commented 4 years ago

Cool merging now. Thanks 😊

sdiehl commented 4 years ago

1.0.2 is on Hackage now. https://hackage.haskell.org/package/galois-field-1.0.2