是否可以将可区分联合标记的类型传递给另一个函数,以便它可以将其用于模式匹配?
我的意思的非工作示例:
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)
如果案例之间没有语义重叠,则可区分联合效果最好。
在您的示例中,每个案例都包含具有相同含义的相同组件,astring
表示“动物的名称”。但这是语义重叠!然后,歧视性工会将迫使您做出您不想做的区分:您don't想要被迫区分“猪名”和“牛名”;你只想想“动物的名字”。
让我们创建一个更适合的类型:
type Animal = Pig | Cow | Fish
type Pet = Animal * string
let animals = [(Pig, "Mike"); (Fish, "Eve"); (Pig, "Romeo")
使用该类型,过滤掉非Pig
s 是单行:
animals |> List.filter (fst >> (=) Pig)
如果不是每个动物都有名字,请使用选项类型:
type Pet = Animal * string option
You would如果您知道,比如说,每个动物,请对您的动物使用歧视联盟Pig
有名字,但没有Fish
确实:这些情况没有重叠。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)