F#和否定匹配 [英] F# and negative match

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

问题描述

我有一个区别类型:

type Item =
    | Normal of string * float32
    | Special1 of Item
    | Special2 of Item

我有一个使用这种类型的函数:

And I have a function using this type:

let rec calcItem (i: Item ) =
    match i with
    | Normal(_, p) -> p
    | Special1(g) | Special2(g) -> (calcItem g) + 1

对于我来说, Special_ n 类型将以相同的形式定义.所以我想知道是否可以使用通配符模式来匹配所有这些类型. _匹配项不起作用,因为它不接受参数.

In my case, the Special_n types will be defined in the same form. So I am wondering if it is possible to use wildcard pattern to match all these types. The _ match does not work, because it does not accept arguments.

推荐答案

类似于这一个

正如那里所解释的,您可以使用反射或重新设计DU(这是我的建议).

As explained there you can use reflection or redesign your DU (this is what I would recommend).

反射:

open Microsoft.FSharp.Reflection

type Item =
    | Normal of string * float32
    | Special1 of Item
    | Special2 of Item

let innerValue a =
    FSharpValue.GetUnionFields (a, a.GetType())
    |> snd
    |> Seq.head
    :?> Item

let rec calcItem (i: Item ) =
    match i with
    | Normal (_, p) -> p
    | specialN      -> calcItem (innerValue specialN) + 1.0f

重新设计DU:

type Item =
    | Normal of string * float32
    | Special of int * Item

let rec calcItem (i: Item ) =
    match i with
    | Normal  (_, p) -> p
    | Special (_, g) -> calcItem g + 1.0f

这篇关于F#和否定匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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