From 9ccfc80ede22a97ff91e4414768b9dfdaafdd029 Mon Sep 17 00:00:00 2001 From: Taylor Fausak Date: Sun, 18 Apr 2021 14:37:02 +0000 Subject: [PATCH] Add some lossy instances --- src/lib/Witch/Instances.hs | 9 +++++++++ src/test/Main.hs | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/lib/Witch/Instances.hs b/src/lib/Witch/Instances.hs index be4054f..d205380 100644 --- a/src/lib/Witch/Instances.hs +++ b/src/lib/Witch/Instances.hs @@ -643,6 +643,9 @@ instance TryCast.TryCast Double Rational where tryCast = maybeTryCast $ \s -> if isNaN s || isInfinite s then Nothing else Just $ toRational s +instance Cast.Cast Double Float where + cast = realToFrac + -- Ratio instance Integral a => Cast.Cast a (Ratio.Ratio a) where @@ -652,6 +655,12 @@ instance (Eq a, Num a) => TryCast.TryCast (Ratio.Ratio a) a where tryCast = maybeTryCast $ \s -> if Ratio.denominator s == 1 then Just $ Ratio.numerator s else Nothing +instance Cast.Cast Rational Float where + cast = fromRational + +instance Cast.Cast Rational Double where + cast = fromRational + -- Fixed instance Cast.Cast Integer (Fixed.Fixed a) where diff --git a/src/test/Main.hs b/src/test/Main.hs index 78f7e2c..0a99622 100644 --- a/src/test/Main.hs +++ b/src/test/Main.hs @@ -1349,6 +1349,12 @@ main = Hspec.hspec . Hspec.describe "Witch" $ do test $ f (1 / 0) `Hspec.shouldSatisfy` Either.isLeft test $ f (-1 / 0) `Hspec.shouldSatisfy` Either.isLeft + Hspec.describe "Cast Double Float" $ do + let f = Witch.cast @Double @Float + test $ f 0 `Hspec.shouldBe` 0 + test $ f 0.5 `Hspec.shouldBe` 0.5 + test $ f (-0.5) `Hspec.shouldBe` (-0.5) + -- NonEmpty Hspec.describe "TryCast [a] (NonEmpty a)" $ do @@ -1376,6 +1382,18 @@ main = Hspec.hspec . Hspec.describe "Witch" $ do test $ f 0 `Hspec.shouldBe` Right 0 test $ f 0.5 `Hspec.shouldSatisfy` Either.isLeft + Hspec.describe "Cast Rational Float" $ do + let f = Witch.cast @Rational @Float + test $ f 0 `Hspec.shouldBe` 0 + test $ f 0.5 `Hspec.shouldBe` 0.5 + test $ f (-0.5) `Hspec.shouldBe` (-0.5) + + Hspec.describe "Cast Rational Double" $ do + let f = Witch.cast @Rational @Double + test $ f 0 `Hspec.shouldBe` 0 + test $ f 0.5 `Hspec.shouldBe` 0.5 + test $ f (-0.5) `Hspec.shouldBe` (-0.5) + -- Fixed Hspec.describe "Cast Integer (Fixed a)" $ do