Search code examples
haskelldhall

Is there a way to generate a dhall schema from an haskell datatype?


I'm trying to rewrite a BIG yaml configuration file used in Haksell applicationusing dhall. To do so I'm using json-to-dhall which requires a SCHEMA which is the type of the resuting expression. The problem is the actual schema is almost impossible to write manually as involves lots of sum types (and nested sum types). I tried to generate the schema by converting manually some parts of the yaml to dhall, and run dhall type. This give a schema that I can use with jston-to-dhall later. This works for simple types, but now I'm facing the problem with unions (of unions). Dhall needs type annotations to write the file I'm using to generate the type ... So I was wondering is there a way (either using a tool or modifying my haskell application) to either dump an Haskell data to a correct dhall file or at least generate the schema from the Haskell type.


Solution

  • Yes, you can generate the Dhall type from the Haskell type.

    Here is an example of how to do so:

    {-# LANGUAGE DeriveGeneric    #-}
    {-# LANGUAGE DeriveAnyClass   #-}
    {-# LANGUAGE TypeApplications #-}
    
    import Data.Either.Validation (Validation(..))
    import Data.Text (Text)
    import Dhall (FromDhall)
    import GHC.Generics (Generic)
    import Numeric.Natural (Natural)
    
    import qualified Data.Text.IO as Text.IO
    import qualified Dhall
    import qualified Dhall.Core
    
    data Mood = Happy | Sad
        deriving (Generic, FromDhall)
    
    data Person = Person { age :: Natural, name :: Text, mood :: Mood }
        deriving (Generic, FromDhall)
    
    main :: IO ()
    main = do
        case Dhall.expected (Dhall.auto @Person) of
            Success result -> Text.IO.putStrLn (Dhall.Core.pretty result)
            Failure errors -> print errors
    

    ... which outputs:

    $ runghc ./example.hs
    { age : Natural, name : Text, mood : < Happy | Sad > }