F#:解构绑定有歧视的联合 [英] F#: Destructuring bind with a discriminated union

查看:113
本文介绍了F#:解构绑定有歧视的联合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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
    • http://ideone.com/cS9bK0
    • 当我取消最后一行的注释时,编译器将拒绝抱怨的代码

      When I uncomment the last line, the compiler rejects the code complaining

      /home/rRiy1O/prog.fs(16,19):错误FS0039:未定义值或构造函数'r'
      /home/rRiy1O/prog.fs(16,21):错误FS0039:未定义值或构造函数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时不允许使用枚举吗?

      Is it not allowed to use enumerations in destructuring let?

      但是首先,即使当我注释掉最后一行时...我在这里做什么 am ?这是输出:

      But first, even when I comment out the last line... what am I doing here? Here's the output:

      A (1, 2)
      B 1 2
      D Some (1, 2)
      

      更新

      记录下来,这是固定版本:

      Update

      For the record, here's the fixed version:

      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
        • 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.

          You are actually defining a function named Some, with two arguments, r and s, passed in tupled form.

          为正确地进行销毁,您需要添加括号:

          For correct destructuring, you need to add parentheses:

          let (Some (r, s)) = y
          

          偶然地,在try块内发生了同样的事情:行let None = y创建了一个名为None且等于y的新值.

          Incidentally, same thing happens inside the try block: the line let None = y creates a new value named None and equal to y.

          这篇关于F#:解构绑定有歧视的联合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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