在 Haskell 中,为什么非穷举模式不是编译时错误? [英] In Haskell, why non-exhaustive patterns are not compile-time errors?

查看:31
本文介绍了在 Haskell 中,为什么非穷举模式不是编译时错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是为什么我会得到功能中的非穷尽模式......"?当我调用 Haskell 子字符串函数时?

我知道使用 -Wall,GHC 可以针对非穷尽模式发出警告.我想知道默认情况下不使其成为编译时错误的原因是什么,因为总是可以显式定义部分函数:

I understand that using -Wall, GHC can warn against non-exhaustive patterns. I'm wondering what's the reason behind not making it a compile-time error by default given that it's always possible to explicitly define a partial function:

f :: [a] -> [b] -> Int
f [] _  = error "undefined for empty array"
f _ []  = error "undefined for empty array"
f (_:xs) (_:ys) = length xs + length ys

这个问题不是针对 GHC 的.

The question is not GHC-specific.

是不是因为...

  • 没有人想要强制使用 Haskell 编译器来执行这种分析吗?
  • 非穷举模式搜索可以找到一些但不是所有案例?
  • 部分定义的函数被认为是合法的并且经常使用,不会强加上面显示的那种构造?如果是这种情况,您能否向我解释为什么非穷举模式有用/合法?

推荐答案

在某些情况下,您不介意模式匹配并非详尽无遗.例如,虽然这可能不是最佳实现,但我认为如果不编译它不会有帮助:

There are cases where you don't mind that a pattern match is non-exhaustive. For example, while this might not be the optimal implementation, I don't think it would help if it didn't compile:

fac 0 = 1
fac n | n > 0 = n * fac (n-1)

这不是详尽的(负数不匹配任何情况)对于阶乘函数的典型用法并不重要.

That this is non-exhaustive (negative numbers don't match any case) doesn't really matter for the typical usage of the factorial function.

此外,如果模式匹配是详尽无遗的,通常也可能无法由编译器决定:

Also it might not generally be possible to decide for the compiler if a pattern match is exhaustive:

mod2 :: Integer -> Integer
mod2 n | even n = 0
mod2 n | odd n  = 1

这里应该涵盖所有情况,但编译器可能无法检测到它.由于守卫可以是任意复杂的,编译器不能总是决定模式是否是详尽无遗的.当然这个例子最好用否则编写,但我认为它也应该以其当前的形式编译.

Here all cases should be covered, but the compiler probably can't detect it. Since the guards could be arbitrarily complex, the compiler cannot always decide if the patterns are exhaustive. Of course this example would better be written with otherwise, but I think it should also compile in its current form.

这篇关于在 Haskell 中,为什么非穷举模式不是编译时错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆