F#:使用区分联合解构绑定(bind)

标签 f# pattern-matching variable-declaration let destructuring

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
  • http://ideone.com/cS9bK0

  • 当我取消注释最后一行时,编译器会拒绝提示的代码

    /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
    
  • http://ideone.com/7qL9mH

  • 输出:
    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 的函数,有两个参数,rs ,以元组形式传递。

    为了正确解构,您需要添加括号:
    let (Some (r, s)) = y
    

    顺便说一句,try 内部也发生了同样的事情。 block :行let None = y创建一个名为 None 的新值等于y .

    关于F#:使用区分联合解构绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36234637/

    相关文章:

    f# - 修改 StringFormat 的函数

    f# - 如何从构建脚本中调用另一个 FAKE 构建脚本?

    algorithm - 在 Go 中查找配对排列

    开源项目中的C99混合声明和代码?

    f# - F#的BigInteger中是否可以替代Pow?

    f# - 了解 F# 值限制错误

    haskell - 测量二叉树大小的函数

    javascript - 在javascript中测试2个字符串之间的常用词

    c++ - 声明变量时 : variable not declared in this scope

    javascript - 在循环中,是重新定义全局变量更好,还是一遍又一遍地重新声明和重新定义局部变量更好,还是没有区别?