elm / error-message-catalog

A catalog of broken Elm programs / data to improve error messages
BSD 3-Clause "New" or "Revised" License
174 stars 17 forks source link

more informative Maybe error #342

Open Hasimir0 opened 3 years ago

Hasimir0 commented 3 years ago

This is the first time I create an Issue... I hope I'm doing it right >_<

Use case: the user passes to a function a Maybe type without explicitly/correctly declaring how to handle all alternatives (mostly the Nothing case).


In the model I have a {segment : Maybe Segment}

where...

type alias Segment = { kind : Int , detail : Int , openings : Int } I have a function that goes like this... revealSomeplace model = let thisSegment = model.segment in if thisSegment.kind < 4 then let passageText = case thisSegment.detail of 1 -> "an ascending passage" 2 -> "a descending passage" 3 -> "a twisting passage" 4 -> "a forking passage" 5 -> "an unstable passage" 6 -> "an obstructed passage" _ -> "error" in [passageText]

I get the error that thisSegment is of type Maybe.Maybe Segment but the fuction needs a record with a kind field.`


Current error: the compiler tells me that I am passing a Maybe type but the compiler expects something different this leads me to think that I have a type problem, some kind of mismatch instead what I needed to do was to cover the Nothing case

Suggestion: if the problem is that not all cases are covered... it would be nice if the compiler told me THAT, instead of insisting that there is some kind of type mismatch. "it seems you are using a Maybe type but I can't find a definition of what happens in case of Nothing"

NduatiK commented 3 years ago

There is a type mismatch (2 actually).

  1. When you write thisSegment.kind < 4, the compiler should complain. You basically saying "do the following when kind is less than 4", but what happens if thisSegment is Nothing? You would be telling the compiler to access .kind from Nothing!
  2. You can't actually access thisSegment.detail because thisSegment might be Nothing.

Try unwrapping the Maybe using something like

revealSomeplace model =
    case model.segment of
        -- This is the unwrapping
    Just thisSegment = model.segment ->
            if thisSegment.kind < 4 then
                let
                    passageText =
                        case thisSegment.detail of
                            1 -> "an ascending passage"
                            2 -> "a descending passage"
                            3 -> "a twisting passage"
                            4 -> "a forking passage"
                            5 -> "an unstable passage"
                            6 -> "an obstructed passage"
                            _ -> "error"
                        in
        else 
        -- thisSegment.kind >= 4 
    Nothing ->
        ...

Put differently, you need to cover the Just InnerType case and the Nothing; not just the InnerType case