如何在 Elm 中编码和解码简单的自定义类型?

Ali*_*vin 5 json custom-type elm

在 Elm 中,没有本地方法来编码/解码自定义类型。这使得向 JS 发送和接收自定义类型的值变得困难。我有一段时间很困惑,想知道如何处理像下面这样的简单自定义类型?

type MyCustomType
  = A
  | B
  | C
Run Code Online (Sandbox Code Playgroud)

Ali*_*vin 7

这是如何对任何自定义类型进行编码和解码的快速简单的演示。

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

type MyCustomType
  = A
  | B
  | C
Run Code Online (Sandbox Code Playgroud)

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

encodeMyCustomType : MyCustomType -> Encode.Value
encodeMyCustomType myCustomType =
  Encode.string <|
    case myCustomType of
      A -> "A"
      B -> "B"
      C -> "C"
Run Code Online (Sandbox Code Playgroud)

解码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"
    )
Run Code Online (Sandbox Code Playgroud)