evancz / guide.elm-lang.org

My book introducing you to Elm!
https://guide.elm-lang.org/
Other
321 stars 186 forks source link

Add hint about order sensitivity of map function (json decode) #253

Open maxzirps opened 4 years ago

maxzirps commented 4 years ago

Programming background: >2 years javascript Learning Elm to learn functional programming and its concepts I was confused by the fact that the map function of json decode is order sensitive,

so if my JSON response looks like this:

{"name": "Willy Wonka",
 "address": "Chocolate Factory"}

and I decode it with:

decoder: Decoder Person
decoder = 
  JD.map2 Question
    (field "address" string)
    (field "name" string)

the values are assigned to the wrong fields.

teehemkay commented 3 years ago

Isn't this explicit in map2 type signature: map2 : (a -> b -> result) -> Decoder a -> Decoder b -> Decoder result

Also remember that "the order of arguments in the record constructor match the order of fields in the type alias!" rather then the map2 function.

Hope this helps

David-Klemenc commented 3 years ago

@maxzirps It is not the JSON that must have the fields in order but rather the fact that you are using a Record Constructor:

-- you probably have a Question record

type alias Question = { address: String, name: String }

-- you can create a question with the constructor:

Question "Some Address" "A Name" -- here the order matters!

-- another example

type alias Person = { name: String, age: Int }

Person "Hercules" 41 -- creates a Person record

The main thing to notice is that in the decoder Question is used as a constructor (... a function). I believe this usage is a bit tricky to notice. If you wold decode the Question to a tuple it would look like so:

type alias Question = (String, String) -- defined as a tuple

decoder: Decoder Question
decoder = 
  JD.map2 Tuple.pair
    (field "address" string)
    (field "name" string)