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

查看:83
本文介绍了如何在"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 whatever = function ...let whatever 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天全站免登陆