open System
let x = (1, 2)
let (p, q) = x
printfn "A %A" x
printfn "B %A %A" p q
let y = Some(1, 2)
try
let None = y
()
with
| ex -> printfn "C %A" ex
let Some(r, s) = y
printfn "D %A" y
// printfn "E %A %A" r s
当我取消注释最后一行时,编译器会拒绝提示的代码
/home/rRiy1O/prog.fs(16,19): error FS0039: The value or constructor 'r' is not defined
/home/rRiy1O/prog.fs(16,21): error FS0039: The value or constructor 's' is not defined
解构中是否允许使用枚举
let
?但首先,即使我注释掉最后一行......我在这里做什么?这是输出:
A (1, 2)
B 1 2
D Some (1, 2)
更新
作为记录,这是固定版本:
open System
let x = (1, 2)
let (p, q) = x
printfn "A %A" x
printfn "B %A %A" p q
let y = Some(1, 2)
try
let (None) = y
()
with
| ex -> printfn "C %A" ex
let (Some(r, s)) = y
printfn "D %A" y
printfn "E %A %A" r s
输出:
A (1, 2)
B 1 2
C MatchFailureException ("/home/MBO542/prog.fs",10,6)
D Some (1, 2)
E 1 2
完美的。
最佳答案
你尝试解构的方式y
:
let Some(r, s) = y
您实际上是在定义一个名为
Some
的函数,有两个参数,r
和 s
,以元组形式传递。为了正确解构,您需要添加括号:
let (Some (r, s)) = y
顺便说一句,
try
内部也发生了同样的事情。 block :行let None = y
创建一个名为 None
的新值等于y
.
关于F#:使用区分联合解构绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36234637/