Last active
April 3, 2021 13:04
-
-
Save ftzm/077f4497ed048b7fa57c789ca22ab8bd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE OverloadedStrings #-} | |
{-# LANGUAGE DeriveGeneric #-} | |
{-# LANGUAGE FlexibleInstances #-} | |
{-# LANGUAGE TypeApplications #-} | |
{-# LANGUAGE FlexibleContexts #-} | |
module HKD where | |
import GHC.Generics | |
import Data.Generic.HKD | |
import Data.Aeson | |
import Data.Maybe | |
import Data.Barbie | |
import Data.Functor.Identity | |
data Contact = Contact | |
{ name :: String | |
, address :: String | |
} deriving (Eq, Generic, Show) | |
type MaybeContact = HKD Contact Maybe | |
instance FromJSON Contact | |
instance FromJSON MaybeContact | |
-- | Update fields in an Identity HKD with Just values from a Maybe HKD | |
update :: (ProductB b) => b Identity -> b Maybe -> b Identity | |
update initial update = bzipWith f initial update | |
where | |
f i u = flip fromMaybe u <$> i | |
-- | Convenience function to avoid manual Identity wrapping | |
updateUnwrapped d x = runIdentity . construct $ update (deconstruct @Identity d) x | |
initialContact = Contact "Matthew" "home" | |
contactUpdate :: MaybeContact | |
contactUpdate = fromJust $ decode "{\"address\": \"new home\"}" | |
-- >>> contactUpdate | |
-- Contact {name = Nothing, address = Just "new home"} | |
-- >>> updateUnwrapped initialContact contactUpdate | |
-- Contact {name = "Matthew", address = "new home"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment