Skip to content

Instantly share code, notes, and snippets.

@kana-sama
Created July 30, 2021 17:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kana-sama/ca7431dc3e60315be38827c41a43c576 to your computer and use it in GitHub Desktop.
Save kana-sama/ca7431dc3e60315be38827c41a43c576 to your computer and use it in GitHub Desktop.
{-# 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