Question about exhaustive checks for pattern matching

** Spoiler alert if you are taking Coursera course Programming Languages Part A **

While I was translating the course assignments from SML to ReScript I came across an interesting situation. The following code in the playground link gives a warning that I forgot to handle a possible case of an empty list when it is impossible for the code reach that section of code if the initial list is an empty list. Even from the compiled JavaScript you can see that the section of code that generates the warning will never be reached if an empty list (array in the case of the JS code).

So I was curious if it is just a limitation of the exhaustiveness checking or are you always expected to check for nullish values regardless when using pattern matching?

https://rescript-lang.org/try?code=DYUwLgBAlgzg8sAJiAThAvBAFIghmEARgBoI8CAmASgwD4IBvAKAglEiwE8SIBbHxIRqZyRFm3DZOFUrxllqGMvhAUm47hAA8EaRAA++3YQzpMegGQW+JnXINGuJs+YoQrN05nsfB2hVRMAL7q7BAA9kggMJCYWAD6ojDC9MysMADuUGAAxgAWEIkqMIziRsCwYAxBdBAAcuEAdiBlhbVprJ1hKCA5EVExDc28AA5gnEo4xSmlnXMQmdn5ygQlHfMGbJUMeYg16PS74hvl27ukAHRXYMD7qccbXZK4jSWYkciDTSCj41g3gUe81gCGQKCw5wgL2SEAA-BBdhAAFxQ14PDYhIGY+bYuYAZXCvBAWA+0TAQx+Y04CSSVEBnWxISCQA

Hi @kay-tee, my understanding is that the exhaustiveness checking is based on types, not on logic in your code. So when doing a switch on a list then you will still need to cover all possible cases independent of any surrounding logic.

2 Likes

To add to @kevanstannard’s response, it’s possible to write code that’s unreachable. One general practice is to add a comment explaining the why the code is unreachable with an assert false statement.

| list{} => /* Proof this is unreachable goes here. */ assert false

That being said, those cases should really be avoided unless absolutely necessary (and usually only in very complex algorithms that can’t be fully expressed in the type system). If you can prove that a particular case isn’t possible, then you should be able to reflect that in the types you’re using.

In this case, it’s a sign that you may need to rework your code. You should either handle the empty list case in the recursive function instead of the outer function (probably the easiest) or use a data type that can’t be empty (probably more advanced).

2 Likes

Okay, I see now. The exhaustiveness check is about covering all possible values for the type. The original problem came before the pattern matching lesson and instead of writing a solution that catered to pattern matching I was trying to do a one for one conversion using pattern matching in place of the if-else expressions.