Created
July 30, 2021 17:50
-
-
Save kana-sama/ca7431dc3e60315be38827c41a43c576 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 BlockArguments #-} | |
{-# LANGUAGE DataKinds #-} | |
{-# LANGUAGE DerivingStrategies #-} | |
{-# LANGUAGE KindSignatures #-} | |
{-# LANGUAGE NamedFieldPuns #-} | |
{-# LANGUAGE ScopedTypeVariables #-} | |
{-# LANGUAGE TypeApplications #-} | |
import Data.Aeson (FromJSON (..), decode, withObject, (.:)) | |
import Data.Proxy (Proxy (..)) | |
import Data.String (fromString) | |
import GHC.TypeLits (KnownSymbol, SomeSymbol (..), Symbol, someSymbolVal, symbolVal) | |
data X = X {value :: Int} | |
deriving stock (Show) | |
newtype XWithKey (key :: Symbol) = XWithKey X | |
instance KnownSymbol key => FromJSON (XWithKey key) where | |
parseJSON = withObject "X" \v -> do | |
value <- v .: fromString (symbolVal (Proxy :: Proxy key)) | |
pure (XWithKey X {value}) | |
main :: IO () | |
main = do | |
key <- fetchKeyFromJIRA | |
SomeSymbol (Proxy :: Proxy key) <- pure (someSymbolVal key) | |
XWithKey x <- fetchX @key | |
print x | |
where | |
fetchKeyFromJIRA :: IO String | |
fetchKeyFromJIRA = pure "hello" | |
fetchX :: KnownSymbol key => IO (XWithKey key) | |
fetchX = | |
case decode (fromString "{\"hello\": 42}") of | |
Just value -> pure value | |
Nothing -> error "wtf" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment