Namaran

Code daily. Without assist.

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 >= 90score >= 70も成り立たず、最後のotherwiseガードも30 >= 50Falseになるので、どの枝にも一致せず非網羅的ガードの実行時エラーになります。このwhereを削除し、Preludeの本来のotherwise(常にTrueな取りこぼしの枝)に戻せば直ります:

verdict :: Int -> String
verdict score
  | score >= 90 = "excellent"
  | score >= 70 = "good"
  | otherwise   = "needs improvement"