所以我正在学习Haskell并且想写一个简单的代码,它只是在字符串中重复两个字母。所以我想出了这个:
repl :: String->String
repl " " = " "
repl (x:xs) = x:x:repl xs
现在编译时我没有收到任何警告,但是当我这样做时发生了运行时错误 repl "abcd"
:
"abcd*** Exception: repl.hs:(2,1)-(3,23): Non-exhaustive patterns in function repl
那么为什么编译器从未报告过这个问题,为什么在有很多像OCaml这样的语言在编译时会清楚地报告这个问题时Haskell会忽略它呢?
默认情况下,模式匹配警告处于关闭状态。你可以用它打开它 -fwarn-incomplete-patterns
或作为一大堆警告的一部分 -W
和 -Wall
。
你可以这样做 ghci
:
Prelude> :set -W
你也可以将旗帜传递给 ghc
当您编译或将其作为编译指示包含在模块顶部时:
{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
对于您的特定程序,它应该给出以下警告:
/home/tjelvis/Documents/so/incomplete-patterns.hs:2:1: Warning:
Pattern match(es) are non-exhaustive
In an equation for ‘repl’: Patterns not matched: []