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

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

问题描述

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



据我所知,使用 -Wall ,GHC可以警告针对非详尽的模式。我想知道是什么原因导致默认情况下没有编译时错误,因为总是可以显式定义一个部分函数:

  f :: [a]  - > [b]  - > 
f [] _ =错误未定义为空数组
f _ [] =错误未定义为空数组
f(_:xs)(_:ys)= length xs + length ys

这个问题不是特定于GHC的。



是否因为...




  • 没有人想强制Haskell编译器执行这种分析?

  • 非穷尽模式搜索可以找到一些但不是全部的情况?
  • 部分定义的函数被认为是合法的,并且经常使用以便不强加上面所示的构造类型?如果是这种情况,您能向我解释为什么非穷举模式有帮助/合法吗? >

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

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

    这是非穷举的(负数don' t匹配任何情况)对于阶乘函数的典型用法无关紧要。



    另外,一般情况下,如果模式匹配是详尽的:

      mod2 :: Integer  - >整数
    mod2 n |即使n = 0
    mod2 n |奇数n = 1

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


    This is a follow-up of Why am I getting "Non-exhaustive patterns in function..." when I invoke my Haskell substring function?

    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
    

    The question is not GHC-specific.

    Is it because...

    • nobody wanted to enforce a Haskell compiler to perform this kind of analysis?
    • a non-exhaustive pattern search can find some but not all cases?
    • partially defined functions are considered legitimate and used often enough not to impose the kind of construct shown above? If this is the case, can you explain to me why non-exhaustive patterns are helpful/legitimate?

    解决方案

    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天全站免登陆