haskell-issues
haskell-issues copied to clipboard
There should be safe constructors for Numeric.Natural
trafficstars
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.