gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:14:20 26 4
gpt4 key购买 nike

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

type MyCustomType
= A
| B
| C

最佳答案

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

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

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"
)

关于json - 如何在 Elm 中编码和解码简单的自定义类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61857966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com