aelve / haskell-issues

An unofficial issue tracker for all things Haskell-related
18 stars 0 forks source link

There should be safe constructors for Numeric.Natural #57

Open mstksg opened 7 years ago

mstksg commented 7 years ago

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.