haskell-issues icon indicating copy to clipboard operation
haskell-issues copied to clipboard

There should be safe constructors for Numeric.Natural

Open mstksg opened this issue 7 years ago • 0 comments

Right now the most common way to construct a Numeric.Natural is by using fromInteger directly or indirectly (like through round or a numeric literal). This is kind of ridiculous, because it inherently makes all usage of the type unsafe, when the entire point of the module and the type is to promote type safety. In a way, it makes the module self-defeating.

I have found one way to safely convert an Integer into a Natural in a way that doesn't require any unsafe casts or calls to fromInteger:

import qualified GHC.TypeNats as TN
import qualified GHC.TypeLits as TL

intToNat :: Integer -> Maybe Natural
intToNat i = TN.natVal <$> TL.someNatVal i

There should be some sort of packInteger :: Integer -> Maybe Natural in the Numeric.Natural module, at the very least, I feel.

mstksg avatar Aug 24 '17 22:08 mstksg