【问题标题】:How to Encode and Decode Simple Custom Types in Elm?如何在 Elm 中对简单的自定义类型进行编码和解码?
【发布时间】:2020-09-03 13:33:54
【问题描述】:

在 Elm 中,没有对自定义类型进行编码/解码的本机方法。这使得向 JS 发送和接收自定义类型的值变得困难。我困惑了一会儿,想知道如何处理像下面这样的简单自定义类型?

type MyCustomType
  = A
  | B
  | C

【问题讨论】:

标签: json elm custom-type


【解决方案1】:

这是一个关于如何编码和解码任何自定义类型的快速简单的演示。

假设你有一个这样的自定义类型:

type MyCustomType
  = A
  | B
  | C

您可以将MyCustomType直接编码为字符串:

encodeMyCustomType : MyCustomType -> Encode.Value
encodeMyCustomType myCustomType =
  Encode.string <|
    case myCustomType of
      A -> "A"
      B -> "B"
      C -> "C"

解码MyCustomType 稍微复杂一些。您需要使用Decode.andThen 来检查找到了哪个变体,如果没有找到有效的变体,请使用Decode.fail

Decode.string |>
  Decode.andThen
    (\str ->
      case str of
        "A" -> Decode.succeed A
        "B" -> Decode.succeed B
        "C" -> Decode.succeed C
        _ -> Decode.fail "Invalid MyCustomType"
    )

【讨论】:

    猜你喜欢
    • 2011-08-11
    • 2021-01-11
    • 2021-11-23
    • 1970-01-01
    • 1970-01-01
    • 2017-09-13
    • 2017-03-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多