Skip to content

Commit edc2e19

Browse files
Add Data.Complex instances
1 parent c41604b commit edc2e19

File tree

2 files changed

+20
-0
lines changed

2 files changed

+20
-0
lines changed

src/Data/Aeson/Types/FromJSON.hs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,7 @@ import Data.Aeson.Types.Internal
9393
import Data.Aeson.Decoding.ByteString.Lazy
9494
import Data.Aeson.Decoding.Conversion (unResult, toResultValue, lbsSpace)
9595
import Data.Bits (unsafeShiftR)
96+
import Data.Complex (Complex(..))
9697
import Data.Fixed (Fixed, HasResolution (resolution), Nano)
9798
import Data.Functor.Compose (Compose(..))
9899
import 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

src/Data/Aeson/Types/ToJSON.hs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ import Data.Aeson.Types.Internal
6767
import qualified Data.Aeson.Key as Key
6868
import qualified Data.Aeson.KeyMap as KM
6969
import Data.Bits (unsafeShiftR)
70+
import Data.Complex (Complex(..))
7071
import Data.DList (DList)
7172
import Data.Fixed (Fixed, HasResolution, Nano)
7273
import 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

14251436
instance HasResolution a => ToJSON (Fixed a) where
14261437
toJSON = Number . realToFrac

0 commit comments

Comments
 (0)