在函数式编程中,不完整的模式匹配被认为是不好的做法 [英] In Functional Programming, is it considered a bad practice to have incomplete pattern matchings

查看:130
本文介绍了在函数式编程中,不完整的模式匹配被认为是不好的做法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常认为在Haskell或F#等函数式语言中使用非穷举模式加工是不好的做法,这意味着指定的例子并不涵盖所有可能的输入案例?

特别是,我是否应该允许代码失败,出现 MatchFailureException 等等,或者我应该总是覆盖所有情况并在必要时显式抛出错误?



示例:

  let head(x :: xs)= x 



 让头列表= 
匹配列表中的
| x :: xs - > x
| _ - > failwith将头部应用于空列表

F#(与Haskell不同)给出了第一个代码的警告,因为 [] -case没有被覆盖,但是为了简洁起见,我可以忽略它而不破坏函数式约定吗?毕竟MatchFailure的确能说明问题...

解决方案

如果您使用构造函数<$完成模式匹配c $ c> [] 而不是捕获所有 _ ,编译器将有机会告诉您再次查看该函数警告当天有人向列表添加第三个构造函数。



我和我的同事在一个大的OCaml项目(200,000多行)上工作,强迫自己避免部分模式匹配警告(即使这意味着不时写入 | ... - >不断声明false )并避免所谓的脆弱模式匹配(模式匹配以这样的方式编写,使得构造函数的添加可能不是检测到)。我们认为可维护性好处。

Is it generally considered a bad practice to use non-exhaustive pattern machings in functional languages like Haskell or F#, which means that the cases specified don't cover all possible input cases?

In particular, should I allow code to fail with a MatchFailureException etc. or should I always cover all cases and explicitly throw an error if necessary?

Example:

let head (x::xs) = x

Or

let head list = 
    match list with
    | x::xs -> x
    |    _  -> failwith "Applying head to an empty list"

F# (unlike Haskell) gives a warning for the first code, since the []-case is not covered, but can I ignore it without breaking functional style conventions for the sake of succinctness? A MatchFailure does state the problem quite well after all ...

解决方案

If you complete your pattern-matchings with a constructor [] and not the catch-all _, the compiler will have a chance to tell you to look again at the function with a warning the day someone adds a third constructor to lists.

My colleagues and I, working on a large OCaml project (200,000+ lines), force ourselves to avoid partial pattern-matching warnings (even if that means writing | ... -> assert false from time to time) and to avoid so-called "fragile pattern-matchings" (pattern matchings written in such a way that the addition of a constructor may not be detected) too. We consider that the maintainability benefits.

这篇关于在函数式编程中,不完整的模式匹配被认为是不好的做法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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