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.
Asked
Active
Viewed 444 times
5

mb14
- 22,276
- 7
- 60
- 102
1 Answers
8
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 > }

Gabriella Gonzalez
- 34,863
- 3
- 77
- 135
-
Thanks for the quick answer. Your example indeed works, but I can't make it work in my case because my data needs to be an instance of `Interpret` which is pretty much impossilbe to do. My data all have `Int`, `Map` etc ... which doesn't have `Interpret` instances by default. I could extract my types and modify it to make it `interpretable` then generate this way the schema, convert my yaml to dhall. I could then use dhall to generate yaml which then could be convert to the original datat type. Unfortunately , I don't have time for that . – mb14 Jul 01 '19 at 09:17
-
This answer doesn't seem to work anymore. I am trying to get the Dhall schema for some Haskell types now too, and from the docs I can't figure it out. I made the trivial changes to your example like using FromDhall instead of Interpret, but I get an error about Expector not having an instance of Pretty. Moreover, I tried to print a real value of perspon after deriving ToDhall, but the docs never show how to convert haskell values to dhall. I would really appreciate any clarity on this matter. – Guy Gastineau Sep 04 '21 at 03:00