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

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

问题描述

在 Haskell 或 F# 等函数式语言中使用非穷举模式是否通常被认为是一种不好的做法,这意味着指定的情况未涵盖所有可能的输入情况?

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?

特别是,我应该允许代码因 MatchFailureException 等而失败,还是应该始终涵盖所有情况并在必要时明确抛出错误?

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?

示例:

let head (x::xs) = x

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

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

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.

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

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