相关疑难解决方法(0)

是否可以将区分的联合标记作为参数传递?

是否可以将有区别的联合标记的类型传递给另一个函数,以便它可以用于模式匹配?

我的意思是非工作的例子:

type Animal = Pig of string | Cow of string | Fish of string

let animals = [Pig "Mike"; Pig "Sarah"; Fish "Eve"; Cow "Laura"; Pig "John"]

let rec filterAnimals animalType animals =
    if animals = [] then
        []
    else
        let rest = filterAnimals animalType (List.tail animals)
        match List.head animals with
        |animalType animal -> animal::rest // <- this doesn't work
        |_ -> rest

printfn "%A" (filterAnimals Pig animals)
Run Code Online (Sandbox Code Playgroud)

f# pattern-matching discriminated-union

9
推荐指数
2
解决办法
1273
查看次数

F#和负面匹配

我有一个歧视类型:

type Item =
    | Normal of string * float32
    | Special1 of Item
    | Special2 of Item
Run Code Online (Sandbox Code Playgroud)

我有一个使用这种类型的功能:

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

在我的情况下,Special_ ñ类型将在相同的形式进行定义.所以我想知道是否可以使用通配符模式来匹配所有这些类型.该_比赛是不行的,因为它不接受参数.

f# pattern-matching

2
推荐指数
2
解决办法
416
查看次数

标签 统计

f# ×2

pattern-matching ×2

discriminated-union ×1