在模式匹配F#中使用类型测试内联解构

编码埃德加

有没有一种方法可以内联使用类型测试模式记录模式

我可以毫无问题地制作记录模式:

let getName3 (a:A) =
  match a with
  | { name = name } -> name

这是一个完全有效的代码:

type IA =
  abstract ID: string

type A =
  { id: string
    name: string }
  interface IA with
    member this.ID = this.id

let getName (a: IA) =
  match a with
  | :? A as a -> a.name
  | _ -> ""

getName
  { id = "1234"
    name = "andrew" }

// val getName : a:IA -> string
// val it : string = "andrew"

这就是我在说的:

let getName2 (a: IA) =
  match a with
  | :? A ({name = name}) as a -> name // Type Test Pattern with Record Pattern inline, maybe even still use binding (as a)
  | _ -> ""

更新资料

我之前的示例太简单了,请改用以下示例:

type IA =
  abstract ID: string

type Stage =
  | FirstStep
  | SecondStep
  
type A =
  { id: string
    name: string option
    stage: Stage
  }
  interface IA with
    member this.ID = this.id

// This is a "nested" pattern inline, I match two Option with one match 
let tryGetName (a: A option) =
  match a with
  | Some { name = (Some name) } -> Some name
  | _ -> None

// This is a more involved nested pattern inline
let tryGetStageAndName (a: A option) =
  match a with
  | Some { name = (Some name); stage = stage } -> Some (stage, name)
  | _ -> None

// This is the syntax I'm looking for:
let tryGetStageAndName2 (a: IA option) =
  match a with
// notice Some (:? A as a) -> is perfectly valid
  | Some (:? A ({ name = (Some name); stage = stage }) -> Some (stage, name)
  | _ -> None

我还想澄清一下,我的问题是关于F#语法的,不是临时场景或围绕特定框的拳击type A,因为我们可以做嵌套的内联模式,有没有办法在类型测试模式之后做模式?

编码埃德加

当前是fslang-uggestions中的建议:

https://github.com/fsharp/fslang-suggestions/issues/830

该语法尚不存在

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章