gpt4 book ai didi

syntax - 如何在 'let' 定义中使用模式匹配?

转载 作者:行者123 更新时间:2023-12-03 23:46:49 25 4
gpt4 key购买 nike

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

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

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

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

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

etc.



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

我知道我可以使用 let whatever = function ...let whatever x = match x with ...得到我想要的结果,但我刚刚发现了另一种模式匹配语法,如果我不知道如何使用它,它会永远困扰着我。

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

最佳答案

AFAIK,在 F# 中无法声明具有相同名称和不同模式匹配签名的多个 let 绑定(bind)。我相信与您正在寻找的最接近的构造是函数规则表达式。

以汽车为例

let car = function
| hd::tl -> hd
| [] -> failwith "empty list"

关于syntax - 如何在 'let' 定义中使用模式匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/455571/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com