Does Vla allow round links?

Assume two data types:

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

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

And this 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" },
  ]
}

It is clear that this JSON can be decoded into non-zero related objects, and this can be determined by the JSON decoder as it decodes the data. Is there a way to decode this JSON and create related data structures? I am not sure how to do this with purely immutable data structures, or if possible.

+4
source share
2 answers

There is a good explanation of recursive data types in Elm here .

If you try to compile your data types, you will get the following error:

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

You can also deal with this in a different way. I prefer to use links IDlike

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 . . , :

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

List String Maybe. [] ( ) "" ( ).

PS: , . , , : , , ( ) X. , ( ): , 3 (1 + 2 ).

+5

, .

:

  • Nothing
  • ,

3 , , "" , , . , , .

Dict , .

+4

Source: https://habr.com/ru/post/1656711/


All Articles