Search code examples
haskelldhall

How to define and use a Haskell-like sum type in Dhall


How can I define a sum type analogous to Haskell's sum types in the Dhall programming language?

For instance, if in Haskell I'd define

data SumProp = Option1 | Option2

My purpose is to define in Dhall a record in which one of its properties has a limited set of possible values:

\(sumPropValue : SumProp) -> { value = sumPropValue }

Solution

  • I believe the standard way this is done is by creating a union type where each option's type is an empty record:

    $ dhall > SumProp <<EOF
    < option1 : {} | option2 : {} >
    EOF
    

    This type permits the values:

    < option1 = {=} | option2 : {} >
    < option2 = {=} | option1 : {} >
    

    though you'll obviously want to name these something convenient like option1 and option2:

    $ dhall > option1 <<EOF
    < option1 = {=} | option2 : {} >
    EOF
    $ dhall > option2 <<EOF
    < option2 = {=} | option1 : {} >
    EOF
    

    This blog article by Gabriel Gonzalez Typed Nix programming using Dhall includes an example, if you search for the definition of the type OperatingSystem.