I have the following type in Haskell, to represent values between 0&23. There's more for handling the arithmetic; elided here for space.
newtype N24 = N_24 Word16
deriving (Enum, Eq, Integral, NFData, Ord, Real, Show)
toN24 ∷ (Integral α, Num α) ⇒ α → N24
toN24 n@(toInteger → n') | n' < toInteger (minBound @N24) = throw Underflow
| n' > toInteger (maxBound @N24) = throw Overflow
| otherwise = N_24 (fromIntegral n)
instance Bounded N24 where
minBound = N_24 0
maxBound = N_24 23
Now, I want to build a similar type for N60. And another for N12.
My question is, can I design a higher-order type(?), e.g., 'BoundedN' such that I could declare
n60 :: BoundedN 60 n12 :: BoundedN 12
that implemented the above, but without having to copy-and-paste the entire definition. I've tried to use Reflection, but honestly, I'm not understanding it and just bouncing on the keys trying to find stuff that works isn't getting me anywhere. I could do it with TemplateHaskell, but I consider that a last resort (at best, it will be relatively hard to read, I fear).
Aucun commentaire:
Enregistrer un commentaire