Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add "nullIsNothing" #36

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
47 changes: 47 additions & 0 deletions src/Data/Aeson/Lens.hs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ module Data.Aeson.Lens
AsNumber(..)
, _Integral
, nonNull
, nullIsNothing
, nullIsDefault
-- * Primitive
, Primitive(..)
, AsPrimitive(..)
Expand Down Expand Up @@ -276,6 +278,51 @@ nonNull :: Prism' Value Value
nonNull = prism id (\v -> if isn't _Null v then Right v else Left v)
{-# INLINE nonNull #-}


-- | Treat a 'Null' value as equivalent to @Nothing@.
--
-- >>> Number 123 ^? nullIsNothing _Integer
-- Just (Just 123)
--
-- >>> Null ^? nullIsNothing _Integer
-- Just Nothing
--
-- >>> "xyz" ^? nullIsNothing _Integer
-- Nothing
--
-- >>> Nothing ^. re (nullIsNothing _Integer)
-- Null
--
-- >>> Just 123 ^. re (nullIsNothing _Integer)
-- Number 123.0
nullIsNothing :: APrism' Value a -> Prism' Value (Maybe a)
nullIsNothing p = withPrism p $ \bk fw ->
let
bk1 Nothing = Null
bk1 (Just x) = bk x
fw1 Null = Right Nothing
fw1 x = Just <$> fw x
in prism bk1 fw1


-- | Treat a 'Null' value as a default
--
-- >>> Number 123 ^? nullIsDefault 0 _Integer
-- Just 123
--
-- >>> Null ^? nullIsDefault 0 _Integer
-- Just 0
--
-- >>> "xyz" ^? nullIsDefault 0 _Integer
-- Nothing
nullIsDefault :: q -> Prism' Value q -> Prism' Value q
nullIsDefault q p = withPrism p $ \bk fw ->
let
fw1 Null = Right q
fw1 x = fw x
in prism bk fw1


------------------------------------------------------------------------------
-- Non-primitive traversals
------------------------------------------------------------------------------
Expand Down