Haskell - haskell中的非详尽模式匹配

Cra*_*ild 15 haskell

所以我正在学习Haskell并想写一个简单的代码,它只是在字符串中重复两个字母.所以我想出了这个:

repl :: String->String
repl " " = " "
repl (x:xs) = x:x:repl xs
Run Code Online (Sandbox Code Playgroud)

现在编译时我没有收到任何警告,但是当我这样做时发生了运行时错误repl "abcd":

"abcd*** Exception: repl.hs:(2,1)-(3,23): Non-exhaustive patterns in function repl
Run Code Online (Sandbox Code Playgroud)

那么为什么编译器从来没有报告过这个问题,为什么在有很多像OCaml这样的语言在编译时清楚地报告这个问题时Haskell会忽略它呢?

Tik*_*vis 14

默认情况下,模式匹配警告处于关闭状态.您可以通过开启-fwarn-incomplete-patterns或警告具有较大软件包的一部分-W-Wall.

你可以这样做ghci:

Prelude> :set -W
Run Code Online (Sandbox Code Playgroud)

您还可以ghc在编译时将标志传递给模块,或将其作为编译指示包含在模块顶部:

{-# OPTIONS_GHC -fwarn-incomplete-patterns #-}
Run Code Online (Sandbox Code Playgroud)

对于您的特定程序,它应该给出以下警告:

/home/tjelvis/Documents/so/incomplete-patterns.hs:2:1: Warning:
    Pattern match(es) are non-exhaustive
    In an equation for ‘repl’: Patterns not matched: []
Run Code Online (Sandbox Code Playgroud)