Skip to content

dict2 is not tail recursive #36

@prasmussen

Description

@prasmussen

I got the following error when decoding a big data structure:

RangeError: Maximum call stack size exceeded

I'm not sure if this repo is actively maintained so I won't bother creating a PR, but here is a tail recursive version of dict2 if anyone needs it:

dict2 : Decoder comparable -> Decoder v -> Decoder (Dict comparable v)
dict2 keyDecoder valueDecoder =
    Decode.keyValuePairs valueDecoder
        |> Decode.andThen (decodeDictFromTuples keyDecoder)


decodeDictFromTuples : Decoder comparable -> List ( String, v ) -> Decoder (Dict comparable v)
decodeDictFromTuples keyDecoder tuples =
    let
        helper : List ( String, v ) -> Dict comparable v -> Decoder (Dict comparable v)
        helper remainingTuples dictAcc =
            case remainingTuples of
                [] ->
                    Decode.succeed dictAcc

                ( strKey, value ) :: rest ->
                    case Decode.decodeString keyDecoder strKey of
                        Ok key ->
                            helper rest (Dict.insert key value dictAcc)

                        Err error ->
                            Decode.fail (Decode.errorToString error)
    in
    helper tuples Dict.empty

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions