From aac3a0e75509c97e3eabce83aca75393453fde8c Mon Sep 17 00:00:00 2001 From: Taylor Fausak Date: Sat, 10 Jul 2021 15:29:03 -0400 Subject: [PATCH] Add instance for converting from rational into fixed --- src/lib/Witch/Instances.hs | 9 +++++++++ src/test/Main.hs | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/src/lib/Witch/Instances.hs b/src/lib/Witch/Instances.hs index a160a52..bc0b958 100644 --- a/src/lib/Witch/Instances.hs +++ b/src/lib/Witch/Instances.hs @@ -1,6 +1,7 @@ {-# OPTIONS_GHC -Wno-orphans #-} {-# LANGUAGE FlexibleInstances #-} {-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TypeApplications #-} module Witch.Instances where @@ -907,6 +908,14 @@ instance From.From Rational Float where instance From.From Rational Double where from = fromRational +-- | TODO +instance Fixed.HasResolution a => TryFrom.TryFrom Rational (Fixed.Fixed a) where + tryFrom = Utility.eitherTryFrom $ \s -> + let t = fromRational s :: Fixed.Fixed a + in if toRational t == s + then Right t + else Left Exception.LossOfPrecision + -- Fixed -- | Uses 'Fixed.MkFixed'. This means @from \@Integer \@Centi 2@ is @0.02@ diff --git a/src/test/Main.hs b/src/test/Main.hs index 2818d4a..9bb1c89 100644 --- a/src/test/Main.hs +++ b/src/test/Main.hs @@ -1448,6 +1448,15 @@ main = runTestTTAndExit $ "Witch" ~: , f 0.5 ~?= 0.5 , f (-0.5) ~?= (-0.5) ] + , "TryFrom Rational (Fixed a)" ~: + let f = hush . Witch.tryFrom @Rational @Fixed.Deci in + [ hush (Witch.tryFrom @Rational @Fixed.Uni 1) ~?= Just 1 + , hush (Witch.tryFrom @Rational @Fixed.Uni 1.2) ~?= Nothing + , f 0.1 ~?= Just 0.1 + , f 1.2 ~?= Just 1.2 + , f 12.3 ~?= Just 12.3 + , f 0.12 ~?= Nothing + ] -- Fixed