5
votes

I'm looking for a way to decode a tuple with two elements in elm.

[[String, Bool]]

The outer list is easy enough to parse with Json.list, but how do I decode the array as a tuple ? I tried the solution from Decode a JSON tuple to Elm tuple but all I get is errors about types of Decoder and Maybe, I assume something changed in elm since that answer. Or maybe I'm missing an import, I don't know.

Thanks

3

3 Answers

4
votes

simplest is

map2 (,) (index 0 string) (index 1 string)
3
votes
1
votes

There's no way to generically convert an array to a tuple.

This is because an array can be of arbitrary length, while a tuple is of a pre-determined length; determined at compile-time.

So to perform the conversion you need to add some constraints, which of course will depend on your problem domain. For example, I may decide that only arrays with two elements can be converted. Like this:

import Array exposing (Array)

arrayToTuple : Array a -> Maybe (a, a)
arrayToTuple array =
    case Array.toList array of
        (a::b::_) -> Just (a, b)
        _ -> Nothing

Due to the differences in length, the function must return a Maybe (a, a); or a similar type which captures the two possible scenarios.

The subtle issue is this: the conversion is lossy and you'll have to account for this at some point.

For example, you can reject ill-suited arrays in the decoder, but then you'll have to account for failed decoding. Or, you can capture the failure in a Maybe, and get sucked into Maybe-land. Either way, you'll have to account for the potential of a failed conversion.