Image for post
Image for post
What is this machine?

Elm types and JSON decoders: cracking the code

My quest to learn and use Elm has gone well with one exception — figuring out JSON decoders. One article helped the most was Brian Hick’s “Lego” post and even better yet his ebook on the subject. I was working through the book today and it finally clicked — that is, I finally saw how JSON decoders do indeed snap together like Legos.

To see how the Legos work, let’s fire up the and see if we can decode an integer. Once we understand this example in detail, we will be prepared to understand more complex (and more realistic) examples.

We did it — the string was converted to , an object of type . But let’s now understand in the inner workings of by looking at the types involved. The gives

Thus, in more abbreviated form, we have the following type signature:

Let’s use the again to get the type signature of (That is, of , since we ). We find

Using (1) and (2), we can answer the question What is the type of the function ? Remember that Elm features partial application of functions. Thus , which according to (1) takes two arguments, yields the one-argument function . Looking at (1) and (2), we see how the Legos fit together, and we find the answer. The type of is .

We can state what we just found in other words: takes a as input and produces a as output. If the input is , the output is . If the input is , the output is . This is in accord with a function having output of type , which can accommodate both the good and the bad outcomes depending on whether the input is valid or not.

Well, that was pretty technical, but then again, this is a technical article. Once you understand this little example, , you have the key to understanding more complicated JSON decoders. Brian Hicks’ article and ebook are highly recommended. To understand the Legos, you need to understand the type signatures and how they fit together.

Homework

Here is a little homework problem. The JSON string

can be decoded as

(a) Do this using , (b) Analyze your work as in the case .

Unrelated

See also: Making drawings with Elm

Written by

jxxcarlson on elm slack, http://jxxcarlson.github.io

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store