Modify the smart designer template.
This may be redundant.
{-
In any case, the standard newtype ...
newtype Foo = Foo Double
Getting Double easy ...
doubleFromFoo :: Foo -> Double doubleFromFoo (Foo x) = x
Enabling Double at runtime requires checking the runtime, do not get around this ...
maybeFooFromDouble :: Double -> Maybe Foo maybeFooFromDouble x | 0 <= x && x <= 1 = Just (Foo x) | otherwise = Nothing
... if you are not happy to be insecure (and have some social means to ensure that all use of unsafeFooFromDouble truly safe) ...
unsafeFooFromDouble :: Double -> Foo unsafeFooFromDouble = Foo
But if it is a compile-time constant, you can perform a check at compile time without overhead at runtime:
thFooFromDouble :: (Real a, Show a) => a -> Q Exp thFooFromDouble x | 0 <= x && x <= 1 = return $ AppE (VarE 'unsafeFooFromDouble) (LitE (RationalL (toRational x))) | otherwise = fail $ show x ++ " is not between 0 and 1"
And here is how you use this last function:
$(thFooFromDouble 0.3)
Remember that you do not need to put spaces between $ and ( !.
dave4420
source share