gpt4 book ai didi

json - 如何通过 Elm 端口传递联合类型?

转载 作者:行者123 更新时间:2023-12-04 10:35:41 24 4
gpt4 key购买 nike

我在尝试 Elm 时遇到了一个问题。我想通过端口传递联合类型,但出现此错误:

Port `setStorage` is trying to communicate an unsupported type.

34| port setStorage : Model -> Cmd msg
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The specific unsupported type is:

Todo.Importance

The types of values that can flow through in and out of Elm include:

Ints, Floats, Bools, Strings, Maybes, Lists, Arrays,
Tuples, Json.Values, and concrete records.

我已经修改了 Todo example如下:
type alias Task =
{ description : String
, completed : Bool
, editing : Bool
, id : Int
, importance : Importance -- <- this is the new field
}

type Importance
= Normal
| High
| Low

issue看起来已经很老了。一位评论者建议“通过端口和 Json.Decode/Encode 传递 Json.Values”,但究竟如何做到这一点?文档似乎有点不清楚,缺少完整的示例。任何帮助表示赞赏。

最佳答案

我成功了 work使用 Json.Decoder/Encoder。毕竟并没有那么难,尽管为了传递一个联合类型而必须序列化每个字段是一个相当大的负担。

解码器:

modelDecoder : Json.Decoder Model
modelDecoder =
Json.object4 Model
("tasks" := Json.list taskDecoder)
("field" := Json.string)
("uid" := Json.int)
("visibility" := Json.string)

taskDecoder : Json.Decoder Task
taskDecoder =
Json.object5 Task
("description" := Json.string)
("completed" := Json.bool)
("editing" := Json.bool)
("id" := Json.int)
("importance" := Json.string `andThen` importanceDecoder)

importanceDecoder : String -> Json.Decoder Importance
importanceDecoder tag =
case tag of
"Normal" -> Json.succeed Normal
"High" -> Json.succeed High
"Low" -> Json.succeed Low
_ -> Json.fail (tag ++ " is not a recognized tag for Importance")

和编码器:
modelToValue : Model -> Json.Encode.Value
modelToValue model =
Json.Encode.object
[
("tasks", Json.Encode.list (List.map taskToValue model.tasks)),
("field", Json.Encode.string model.field),
("uid", Json.Encode.int model.uid),
("visibility", Json.Encode.string model.visibility)
]

taskToValue : Task -> Json.Encode.Value
taskToValue task =
Json.Encode.object
[
("description", Json.Encode.string task.description),
("completed", Json.Encode.bool task.completed),
("editing", Json.Encode.bool task.editing),
("id", Json.Encode.int task.id),
("importance", importanceToValue task.importance)
]

importanceToValue : Importance -> Json.Encode.Value
importanceToValue importance =
case importance of
Normal -> Json.Encode.string "Normal"
High -> Json.Encode.string "High"
Low -> Json.Encode.string "Low"

关于json - 如何通过 Elm 端口传递联合类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37999504/

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