File tree Expand file tree Collapse file tree 2 files changed +20
-0
lines changed Expand file tree Collapse file tree 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
9393import Data.Aeson.Decoding.ByteString.Lazy
9494import Data.Aeson.Decoding.Conversion (unResult , toResultValue , lbsSpace )
9595import Data.Bits (unsafeShiftR )
96+ import Data.Complex (Complex (.. ))
9697import Data.Fixed (Fixed , HasResolution (resolution ), Nano )
9798import Data.Functor.Compose (Compose (.. ))
9899import Data.Functor.Identity (Identity (.. ))
@@ -1720,6 +1721,14 @@ instance (FromJSON a, Integral a) => FromJSON (Ratio a) where
17201721 then fail " Ratio denominator was 0"
17211722 else pure $ numerator % denominator
17221723
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+
17231732-- | This instance includes a bounds check to prevent maliciously
17241733-- large inputs to fill up the memory of the target system. You can
17251734-- 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
6767import qualified Data.Aeson.Key as Key
6868import qualified Data.Aeson.KeyMap as KM
6969import Data.Bits (unsafeShiftR )
70+ import Data.Complex (Complex (.. ))
7071import Data.DList (DList )
7172import Data.Fixed (Fixed , HasResolution , Nano )
7273import Data.Foldable (toList )
@@ -1421,6 +1422,16 @@ instance (ToJSON a, Integral a) => ToJSON (Ratio a) where
14211422 " numerator" .= numerator r <>
14221423 " denominator" .= denominator r
14231424
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+ ]
14241435
14251436instance HasResolution a => ToJSON (Fixed a ) where
14261437 toJSON = Number . realToFrac
You can’t perform that action at this time.
0 commit comments