Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
maxzirps opened this issue Sep 14, 2020 · 2 comments
Open

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

maxzirps opened this issue Sep 14, 2020 · 2 comments

Comments

@maxzirps
Copy link

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

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

David-Klemenc commented Feb 11, 2021

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants