Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Internal module to expose constructor for Scientific #67

Open
MaxGabriel opened this issue Mar 23, 2019 · 0 comments
Open

Internal module to expose constructor for Scientific #67

MaxGabriel opened this issue Mar 23, 2019 · 0 comments

Comments

@MaxGabriel
Copy link

Hi, I have a newtype over Scientific and I've made a quasi quoter for using it in an expression. However, I believe to make a quasi quoter to use it in a pattern context I would need access to the constructor. Would you be open to adding an Internal module that exposes the constructor for Scientific?

For reference, this is how I create Scientifics in an expression context:

instance Lift Scientific where
  lift sci = 
    let coefficient = Scientific.coefficient sci
        base10Exponent = Scientific.base10Exponent sci
    in [|Scientific.scientific $(TH.lift coefficient) $(TH.lift base10Exponent)|]

-- | Arbitrary-precision value constrained to 0 through 100, inclusive.
newtype Percentage = Percentage Scientific
  deriving (Eq, Show, Read, Ord, ToJSON, Num, Fractional, Real, RealFrac, Lift)

mkPercentage :: Scientific -> Maybe Percentage
mkPercentage sci = if sci >= 0 && sci <= 100 then Just (Percentage sci) else Nothing

-- | Create a 'Percentage' at compile time
-- Usage:
-- > [compilePercentage|100|]
compilePercentage :: QuasiQuoter
compilePercentage = QuasiQuoter
    { quoteExp = quoteExp'
    , quotePat = error "percentage is not supported as a pattern" -- I don't think this can be implemented without access to the Scientific constructor. Maybe with the Num instance though?
    , quoteDec = error "percentage is not supported at top-level"
    , quoteType = error "percentage is not supported as a type"
    }
    where

    quoteExp' :: String -> Q Exp
    quoteExp' s = case (readMay s :: Maybe Scientific) >>= mkPercentage of
      Nothing -> fail $ "Invalid Percentage: " ++ s
      Just percentage -> [| percentage |]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant