如何在“let"定义中使用模式匹配? [英] How do I use pattern matching in 'let' definitions?

查看:28
本文介绍了如何在“let"定义中使用模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚注意到 F# 允许我使用 let 绑定与文字和其他模式,如下所示:

I've just noticed F# allows me to use let bindings with literals and other patterns as follows:

let fib 0 = 1
let exists item [] = false
let car (hd :: tl) = hd
let cdr (hd :: tl) = tl

F# 正确地将这些函数解释为一种模式匹配,因为给了我以下警告:

F# correctly interprets these functions as a kind of pattern matching, because gives me the following warnings:

警告 1 不完整的模式匹配在这个表情上.例如,值1"不会是匹配

Warning 1 Incomplete pattern matches on this expression. For example, the value '1' will not be matched

警告 2 不完整的模式匹配在这个表情上.例如,值 '[_]' 不会是匹配

Warning 2 Incomplete pattern matches on this expression. For example, the value '[_]' will not be matched

这些函数按预期工作,但我想以这种风格定义一个具有完整模式匹配的函数,但是我在 F# 手册中找不到关于这种替代模式匹配语法的任何信息.

These functions work as expected, but I want to define a function in this style with complete pattern matches, however I can't find anything about this alternative pattern matching syntax in the F# manual.

我知道我可以使用 let nothing = function ...letwhatever x = match x with ... 来得到我想要的结果,但我'我刚刚发现了另一种模式匹配的语法,如果我不知道如何使用它,它会永远唠叨我.

I know I can use let whatever = function ... and let whatever x = match x with ... to get the results I want, but I've just discovered yet another syntax for pattern matching and it'll nag at me forever if I don't figure out how to use it.

如何使用上面显示的替代模式匹配语法编写函数?

推荐答案

JaredPar 是对的,F# 没有 Haskell 在这里所做的语法形式.

JaredPar is right, F# doesn't have the syntactic form that Haskell does here.

F# 形式最适用于打破开放的单例区分联合或定义具有不完整匹配的函数(例如在空列表中失败的汽车"示例).这只是因为实际上语言中的所有名称绑定都是通过模式完成的;由于您描述的确切原因,这种句法形式(使用参数模式定义函数)在实践中通常不太有用.

The F# form is mostly useful for breaking open single-case discriminated unions or for defining functions with incomplete matches (like your 'car' example that fails on the empty list). It's simply a consequence of the fact that practically all name-binding in the language is done via patterns; this syntactic form (defining a function using patterns on arguments) is not often too useful in practice, for the exact reason you described.

我认为 Haskell 在句法形式方面做得比 ML 更好,但 F# 的根源在于 ML.好处是 F# 的一个很好的子集可以与 OCaml 交叉编译(这有助于引导 F# 语言和用户社区);缺点是 F# 被一些丑陋/有限的语法卡住"了.

I think Haskell did a number of things better than ML when it comes to syntactic forms, but F#'s roots are in ML. The benefit is that a good subset of F# cross-compiles with OCaml (which helped bootstrap the F# language and user community); the drawback is that F# is 'stuck' with a few bits of ugly/limited syntax.

这篇关于如何在“let"定义中使用模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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