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

Union types generate incorrect code #19

Open
avh4 opened this issue Jul 22, 2016 · 1 comment
Open

Union types generate incorrect code #19

avh4 opened this issue Jul 22, 2016 · 1 comment

Comments

@avh4
Copy link

avh4 commented Jul 22, 2016

This input

type InterestLevel
    = NotAtAllInteresting
    | NotVeryInteresting
    | Neutral
    | Interesting
    | VeryInteresting

yields

fromStringInterestLevel : InterestLevel -> Result String String
fromStringInterestLevel string = 
    case string of
        "Interesting" -> Result.Ok Interesting
        "Neutral" -> Result.Ok Neutral
        "NotAtAllInteresting" -> Result.Ok NotAtAllInteresting
        "NotVeryInteresting" -> Result.Ok NotVeryInteresting
        "VeryInteresting" -> Result.Ok VeryInteresting
        _ -> Result.Err ("Not valid pattern for decoder to InterestLevel. Pattern: " ++ (toString string))

decodeInterestLevel : Json.Decode.Decoder InterestLevel
decodeInterestLevel =
    Json.Decode.string `Json.Decode.andThen` fromStringInterestLevel

encodeInterestLevel : InterestLevel -> Json.Value
encodeInterestLevel =
 toString >> Json.Encode.string

which incorrectly has the type of fromStringInterestLevel : InterestLevel -> Result String String. It should be fromStringInterestLevel : String -> Result String InterestLevel.

Also, the generated code for decodeInterestLevel should be decodeInterestLevel = Json.Decode.customDecoder Json.Decode.string fromStringInterestLevel

@avh4 avh4 changed the title fromString... function is generated with an incorrect type Union types generate incorrect code Jul 22, 2016
@andys8
Copy link
Contributor

andys8 commented Oct 12, 2017

To use the union type I changes the result to have this format and the decoder type instead of Result:

fromStringSize : String -> Decoder Size
fromStringSize string =
    case string of
        "SizeLarge" ->
            Decode.succeed SizeLarge

        "SizeSmall" ->
            Decode.succeed SizeSmall

        _ ->
            Decode.fail ("Not valid pattern for decoder to Size. Pattern: " ++ toString 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

2 participants