top | item 14874085

(no title)

danneu | 8 years ago

Elm's JSON combinators are great.

I'm sure one reason so many people have particular trouble with them is because, according to the survey, the vast majority of them come from a dynamically-typed language where you'd just go `user = JSON.parse(string)`.

I think a lot of people would be helped by tacking a bunch of real-world examples onto the actual Json.Decoder docs like how to decode `[1, [3, 5], 7, 9]` (nested range) into `[1, 3, 4, 5, 7, 9]`. One issue is that it's pretty hard to derive understanding from just function signatures, so a dozen quick-start / cookbook examples gives people something to chew on.

Combinators are really good at forbidding runtime errors which is a central theme of Elm, but it comes at the expense of a steeper learning curve than the weaker alternatives that come to mind: reflection and manual descent.

discuss

order

shakna|8 years ago

> Elm's JSON combinators are great.

> I'm sure one reason so many people have particular trouble

Those two sentences don't really fit together. Elm isn't an academic experiment, which means people need to use it.

If the vast majority of people find it overly difficult, then it probably is.

> come from a dynamically-typed language where you'd just go `user = JSON.parse(string)`

Not just dynamic languages.

Haskell, one of Elm's inspirations, can handle it a hell of a lot easier.

Define an interface, then use it on a string:

    data Coord = Coord { x :: Double, y :: Double }
                 deriving (Show, Generic)
    let req = decode "{\"x\":3.0,\"y\":-1.0}" :: Maybe Coord
I am cheating a bit, as that's the aeson package... But decoding the JSON is a lot simpler than the Elm equivalent, and Haskell doesn't even target web browsers, where JSON is so prevalent.

But, here's another static example, this time, C++.

    auto j3 = json::parse("{ \"happy\": true, \"pi\": 3.141 }");
You can use auto to avoid writing a massive type definition, or you can write it ensure it's correct.

Static typing has nothing to do with not being able to write JSON.parse(string), because it doesn't prevent that. At all.

PhineasRex|8 years ago

I've heard more than one person argue against automatically generated encoders/decoders since it's easy to accidentally introduce breaking changes to your API by renaming a record field / class method.

If that's your view then Elm's approach is a plus for the language since it eliminates a potential pitfall.

always_good|8 years ago

You've given some toy examples, but in the real world you're writing custom decoders. For example, when interoperating with any API that you didn't write.

Your example would lead us to believe that nobody is writing custom decoders in Haskell that look like Elm's decoders, and that's... very misleading.