如何创建具有任意键但键入值的 dhall 模式?

How to create a dhall schema with arbitrary key but typed values?

在 dhall 中,如何为以下 yaml 创建架构?

environment:
    local:
        path: "/path/to/env"
        envvars:
            - var1
            - var2
    stage:
        path: "/path/to/env"
        envvars:
            - var1
            - var2
    prod:
        path: "/path/to/env"
        envvars:
            - var1
            - var2

如您所见,它具有任意键("local"、"stage" 等),但值的类型相同。我相信这是一个相当常见的用例,但我没有在教程中看到它的讨论。

您可以在语言导览中使用Mapdefined in the Prelude and discussed

let Prelude = http://prelude.dhall-lang.org/v16.0.0/package.dhall

let Environment = { path : Text, envvars : List Text }

let EnvironmentSet = { environment : Prelude.Map.Type Text Environment }

in    { environment = toMap
          { local = { path = "/path/to/env", envvars = [ "var1", "var2" ] }
          , stage = { path = "/path/to/env", envvars = [ "var1", "var2" ] }
          , prod = { path = "/path/to/env", envvars = [ "var1", "var2" ] }
          }
      }
    : EnvironmentSet

dhall-to-yaml 生成原始 YAML(模键顺序):

% dhall-to-yaml < tmp.dhall
environment:
  local:
    envvars:
      - var1
      - var2
    path: /path/to/env
  prod:
    envvars:
      - var1
      - var2
    path: /path/to/env
  stage:
    envvars:
      - var1
      - var2
    path: /path/to/env

您还可以通过定义一些函数来创建记录和地图,从而摆脱大部分样板文件。

let Map = http://prelude.dhall-lang.org/v16.0.0/Map/package.dhall

let Environment = { path : Text, envvars : List Text }

let makeEnv =
        λ(name : Text)
      → λ(path : Text)
      → λ(vars : List Text)
      → Map.keyValue Environment name { path = path, envvars = vars }

let makeEnvironmentSet =
      λ(envs : List (Map.Entry Text Environment)) → { environment = envs }

in  makeEnvironmentSet
      [ makeEnv "local" "/path/to/local" [ "localvar1", "localvar2" ]
      , makeEnv "stage" "/path/to/stage" [ "stagevar1", "stagevar2" ]
      , makeEnv "prod" "/path/to/prod" [ "prodvar1", "prodvar2" ]
      ]

dhall-to-yaml{mapKey: k, mapValue: v} 类型的记录转换为 YAML 对象。