Dhall-haskell: Generating Dhall’s type files from Haskell’s instances?

Created on 24 Jan 2019  Â·  6Comments  Â·  Source: dhall-lang/dhall-haskell

Today, I needed to use an Optional on a record with huge type… that I don’t have in Dhall code anywhere.

Since Dhall won’t infer a Nothing _ on its own, I need some Nothing ./MyRecord.type.

Could this MyRecord.type be auto-generated from a given Dhall.Interpret instance (which is also auto-derived!), when building the project?

This would serve as:

  • a type for Nothings,
  • a (kinda-self-)documentation for admins later editing this record,
  • time saver for developers (not needing to update both Haskell and Dhall types).
marshalling

Most helpful comment

@michalrus I would be inclined to treat the Dhall type as the source of truth. There’s already a Dhall.TH module that reads a Dhall expression into an AST at compile time. It would be cool to see additional TH in there that would create a Haskell type from a Dhall expression.

All 6 comments

@michalrus: Yes. Given an Interpret instance for a Haskell type you can print the corresponding Dhall type like this:

{-# LANGUAGE DeriveGeneric    #-}
{-# LANGUAGE DeriveAnyClass   #-}
{-# LANGUAGE TypeApplications #-}

import Dhall (Generic, Interpret, Natural, Text)

import qualified Data.Text.IO
import qualified Dhall
import qualified Dhall.Core

data Example = Example { name :: Text, age :: Natural }
    deriving (Generic, Interpret)

main :: IO ()
main = do
    let expression = Dhall.expected (Dhall.auto @Example)

    Data.Text.IO.putStrLn (Dhall.Core.pretty expression)

... which produces this output when run:

{ name : Text, age : Natural }

Wonderful, thank you! :sparkles:

But, I wonder, what is the recommended approach, if we only consume Dhall files from Haskell? Should the Type file still be adjusted manually?

@michalrus I would be inclined to treat the Dhall type as the source of truth. There’s already a Dhall.TH module that reads a Dhall expression into an AST at compile time. It would be cool to see additional TH in there that would create a Haskell type from a Dhall expression.

Yeah, generating Haskell code from the Dhall type would be consistent with how other IDLs work like Thrift or Protobuf. The main motivation for doing that is that sometimes you need to interoperate with code written in other languages, so you want the source of truth to be language-agnostic (i.e. the interface definition language, which would be Dhall in this case)

I see, thank you, both!

You're welcome! 🙂

Was this page helpful?
0 / 5 - 0 ratings

Related issues

quasicomputational picture quasicomputational  Â·  4Comments

SiriusStarr picture SiriusStarr  Â·  5Comments

jvanbruegge picture jvanbruegge  Â·  4Comments

Gabriel439 picture Gabriel439  Â·  6Comments

aljce picture aljce  Â·  4Comments