haskelldhall

How can I print/encode a value into Dhall?


{-# LANGUAGE DeriveGeneric     #-}
{-# LANGUAGE OverloadedStrings #-}

import Dhall

data Example = Example { foo :: Natural, bar :: Vector Double }
    deriving (Generic, Show)

instance Interpret Example

main :: IO ()
main = do
  putStrLn "Hello, Haskell!"
  x <- input auto "./example.dhall"
  print (x :: Example)

In the above example, how can I instead encode an Example into a dhall value, so essentially a function of type Example -> String? Can't seem to find any reference to printing / encoding in haddocks.


Solution

  • This is how you can pretty-print a Haskell value as the equivalent Dhall expression:

    {-# LANGUAGE DeriveGeneric     #-}
    {-# LANGUAGE DeriveAnyClass    #-}
    {-# LANGUAGE OverloadedStrings #-}
    
    import Dhall (FromDhall, Natural, ToDhall, Vector)
    import Dhall.Pretty (CharacterSet(..))
    import GHC.Generics (Generic)
    
    import qualified Data.Text.Prettyprint.Doc.Render.Text as Prettyprint.Text
    import qualified Dhall
    import qualified Dhall.Pretty
    import qualified Dhall.Core
    
    data Example = Example { foo :: Natural, bar :: Vector Double }
        deriving (FromDhall, Generic, Show, ToDhall)
    
    main :: IO ()
    main = do
      x <- Dhall.input Dhall.auto "./example.dhall"
    
      let expression = Dhall.embed Dhall.inject (x :: Example)
    
      let doc = Dhall.Pretty.prettyCharacterSet Unicode expression
    
      Prettyprint.Text.putDoc doc