Skip to content

Instantly share code, notes, and snippets.

@HirotoShioi
Created November 29, 2018 02:13
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 HirotoShioi/69a63c11e0f73afe01f9182986c052a0 to your computer and use it in GitHub Desktop.
Save HirotoShioi/69a63c11e0f73afe01f9182986c052a0 to your computer and use it in GitHub Desktop.
Done!!!!
import Dhall (Interpret (..), Inject(..))
import qualified Dhall as D
import Dhall.Core (pretty)
import qualified Data.Text as T
import GHC.Generics
import Control.Monad.Trans.State.Strict (evalState)
import Data.Functor.Contravariant
data Person = Person {
pName :: !Text
, pAge :: !Natural
} deriving (Eq, Show, Generic)
instance Interpret Person where
autoWith _ = D.record $
Person <$> D.field "name" D.auto
<*> D.field "age" D.auto
-- Define instance using generics
instance Inject Person where
injectWith _ = contramap GHC.Generics.from (evalState (D.genericInjectWith option) 1)
where
option = D.defaultInterpretOptions {D.fieldModifier = lowerHead . T.drop 1}
-- | I knowwww it's partial function, but I don't think there would be an field with empty key in Dhall files
-- so I'd presume this is safe
lowerHead :: T.Text -> T.Text
lowerHead str = T.toLower $ T.take 1 str <> T.drop 1 str
-- > let p = Person "Hiroto" 10000
-- > pretty $ embed myInject p
-- > "{ name = "hiroto", age = 29 }"
testRoundTrip :: (Inject a, Interpret a, Eq a) => a -> IO Bool
testRoundTrip p = do
person <- D.input D.auto $ pretty $ D.embed D.inject p
return $ p == person
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment