Last active
May 10, 2022 18:01
-
-
Save jespercockx/c5a291d49e77f6343e7362ced0c13a80 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- This is an alternative solution to the problem discussed in the video https://www.youtube.com/watch?v=WplTbki3gCg | |
{-# LANGUAGE RankNTypes, StandaloneDeriving, DeriveAnyClass, TypeApplications, ScopedTypeVariables, GADTs #-} | |
import Data.Scientific | |
import Type.Reflection | |
data AnyRealFloat = AnyRealFloat (forall a. RealFloat a => a) | |
instance Eq AnyRealFloat where | |
instance Ord AnyRealFloat where | |
instance Num AnyRealFloat where | |
instance Fractional AnyRealFloat where | |
fromRational x = AnyRealFloat $ fromRational x | |
instance Floating AnyRealFloat where | |
instance Real AnyRealFloat where | |
instance RealFrac AnyRealFloat where | |
instance RealFloat AnyRealFloat where | |
data AnyIntegral = AnyIntegral (forall a. Integral a => a) | |
instance Eq AnyIntegral where | |
instance Ord AnyIntegral where | |
instance Num AnyIntegral where | |
fromInteger x = AnyIntegral $ fromInteger x | |
AnyIntegral x * AnyIntegral y = AnyIntegral (x * y) | |
instance Real AnyIntegral where | |
instance Enum AnyIntegral where | |
instance Integral AnyIntegral where | |
convertScientific :: forall t. Typeable t => Scientific -> t | |
convertScientific sci = case floatingOrInteger sci of | |
Left (AnyRealFloat floating) | |
| Just HRefl <- typeRep @t `eqTypeRep` typeRep @Float -> floating | |
| Just HRefl <- typeRep @t `eqTypeRep` typeRep @Double -> floating | |
Right (AnyIntegral integer) | |
| Just HRefl <- typeRep @t `eqTypeRep` typeRep @Int -> integer | |
| Just HRefl <- typeRep @t `eqTypeRep` typeRep @Integer -> integer | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment