2026-09-18
Verdict.hs
verdict :: Int -> String
verdict score
| score >= 90 = "excellent"
| score >= 70 = "good"
| otherwise = "needs improvement"
where
otherwise = score >= 50
verdict 30は"needs improvement"を返すつもりですが、実行時にクラッシュします。何が問題で、どう直せばよいでしょうか?
Answer
otherwiseはキーワードではなく、Preludeがotherwise = Trueとして定義している、ただのBoolの値です。このwhereは同じ名前でotherwiseを再定義しており、この関数の中ではotherwiseという名前が指すものがscore >= 50に置き換わってしまいます。verdict 30では、score >= 90もscore >= 70も成り立たず、最後のotherwiseガードも30 >= 50でFalseになるので、どの枝にも一致せず非網羅的ガードの実行時エラーになります。このwhereを削除し、Preludeの本来のotherwise(常にTrueな取りこぼしの枝)に戻せば直ります:
verdict :: Int -> String
verdict score
| score >= 90 = "excellent"
| score >= 70 = "good"
| otherwise = "needs improvement"