File tree 2 files changed +20
-0
lines changed 2 files changed +20
-0
lines changed Original file line number Diff line number Diff line change @@ -93,6 +93,7 @@ import Data.Aeson.Types.Internal
93
93
import Data.Aeson.Decoding.ByteString.Lazy
94
94
import Data.Aeson.Decoding.Conversion (unResult , toResultValue , lbsSpace )
95
95
import Data.Bits (unsafeShiftR )
96
+ import Data.Complex (Complex (.. ))
96
97
import Data.Fixed (Fixed , HasResolution (resolution ), Nano )
97
98
import Data.Functor.Compose (Compose (.. ))
98
99
import Data.Functor.Identity (Identity (.. ))
@@ -1720,6 +1721,14 @@ instance (FromJSON a, Integral a) => FromJSON (Ratio a) where
1720
1721
then fail " Ratio denominator was 0"
1721
1722
else pure $ numerator % denominator
1722
1723
1724
+ instance FromJSON a => FromJSON (Complex a ) where
1725
+ parseJSON = withArray " Complex" $ \ c ->
1726
+ let n = V. length c
1727
+ in if n == 2
1728
+ then (:+) <$> parseJSONElemAtIndex parseJSON 0 c
1729
+ <*> parseJSONElemAtIndex parseJSON 1 c
1730
+ else fail $ " cannot unpack array of length " ++ show n ++ " into a Complex"
1731
+
1723
1732
-- | This instance includes a bounds check to prevent maliciously
1724
1733
-- large inputs to fill up the memory of the target system. You can
1725
1734
-- newtype 'Scientific' and provide your own instance using
Original file line number Diff line number Diff line change @@ -67,6 +67,7 @@ import Data.Aeson.Types.Internal
67
67
import qualified Data.Aeson.Key as Key
68
68
import qualified Data.Aeson.KeyMap as KM
69
69
import Data.Bits (unsafeShiftR )
70
+ import Data.Complex (Complex (.. ))
70
71
import Data.DList (DList )
71
72
import Data.Fixed (Fixed , HasResolution , Nano )
72
73
import Data.Foldable (toList )
@@ -1421,6 +1422,16 @@ instance (ToJSON a, Integral a) => ToJSON (Ratio a) where
1421
1422
" numerator" .= numerator r <>
1422
1423
" denominator" .= denominator r
1423
1424
1425
+ instance ToJSON a => ToJSON (Complex a ) where
1426
+ toJSON (i :+ q) = Array $ V. create $ do
1427
+ mv <- VM. unsafeNew 2
1428
+ VM. unsafeWrite mv 0 (toJSON i)
1429
+ VM. unsafeWrite mv 1 (toJSON q)
1430
+ return mv
1431
+ toEncoding (i :+ q) = E. list id
1432
+ [ toEncoding i
1433
+ , toEncoding q
1434
+ ]
1424
1435
1425
1436
instance HasResolution a => ToJSON (Fixed a ) where
1426
1437
toJSON = Number . realToFrac
You can’t perform that action at this time.
0 commit comments