gpt4 book ai didi

elm - Elm 是否允许循环引用?

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

假设有两种数据类型:

type alias Player = 
{ name : String
, team : Team
}

type alias Team =
{ name : String
, players : List Player
}

而这个 JSON:
{
"players": [
{ "id": 100, "name": "Sam Bradford", "teamId": 200 },
{ "id": 101, "name": "Kyle Rudolph", "teamId": 200 },
{ "id": 102, "name": "Matthew Stafford", "teamId": 201 },
{ "id": 103, "name": "Marvin Jones Jr.", "teamId": 201 },
{ "id": 104, "name": "Golden Tate", "teamId": 201 },
],
"teams": [
{ "id": 200, "name": "Minnesota Vikings" },
{ "id": 201, "name": "Detroit Lions" },
]
}

很明显,这个 JSON 可以被解码为非空链接对象,这可以由 JSON 解码器在解码数据时确定。有没有办法解码这个 JSON 并创建链接的数据结构?我不确定如何使用完全不可变的数据结构来做到这一点,或者是否可能。

最佳答案

Elm here 中对递归数据类型有很好的解释.

如果您尝试编译数据类型,则会收到以下错误:

-- ALIAS PROBLEM ---------------------------------------------------------------

This type alias is part of a mutually recursive set of type aliases.

4|>type alias Player =
5|> { name : String
6|> , team : Team
7|> }

The following type aliases are mutually recursive:

┌─────┐
│ V
│ Player
│ │
│ V
│ Team
└─────┘

You need to convert at least one `type alias` into a `type`. This is a kind of
subtle distinction, so definitely read up on this before you make a fix:
<https://github.com/elm-lang/elm-compiler/blob/0.17.0/hints/recursive-alias.md>

你也可以用另一种方式来处理这个问题。我更喜欢诉诸 ID引用文献,例如
type alias ID = Int

type alias PlayerList = Dict ID PLayer
type alias TeamList = Dict ID Team

type alias Player =
{ name : String
, teamID : ID
}

type alias Team =
{ name : String
, players : List ID
}

更新:您还提到 null您问题中的引用资料。在上面的数据类型中,每个玩家必须有一个团队。如果 team 是一个可选字段,我会定义如下:
type alias Player = 
{ name : String
, teamID : Maybe ID
}

对于 ListString类型,你真的不需要 Maybe类型。使用 [] 可以更轻松地获得空状态(空列表)和 "" (空字符串)。

PS:另一个假设是你有一个特定的需求,在你的模型的每个团队中存储团队成员列表。因为严格来说你不需要:球员名单已经拥有找出哪些球员(如果有)属于 X 队所需的所有数据。
请注意,如果您维护 2-way 引用,则需要大量工作(并且可能导致严重的错误):如果一名球员换队,您需要更新 3 条记录(1 名球员 + 2 条球队记录)。

关于elm - Elm 是否允许循环引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39857251/

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