通配符用于匹配歧视联盟时的类型 [英] Wildcard for type when matching discriminated unions
问题描述
在下面的现实世界中,我做了一个匹配:
type Style = Nice |酷|丑陋的
type Color = Blue |黄色|橙色|灰色|青色
类型ClothingProperties =风格*颜色
类型衣服=
|服装牛仔服饰性能
|服装套头衫
|衬衫服装性能
型人物=
|人物*衣服
让团队= [人物(Jan,牛仔裤(酷炫,蓝色));人(皮特,衬衫(尼斯,青));人(哈利,套头衫(丑陋,灰色))]
让matchPerson person =
与
匹配的人| Person(名字,牛仔裤(Ugly,_)) - > printfn%s穿着丑陋的东西。名称
|人(名字,套衫(丑陋,_)) - > printfn%s穿着丑陋的东西。名称
|人(名字,衬衫(丑陋,_)) - > printfn%s穿着丑陋的东西。名称
| _ - > ()
List.iter(fun x-> matchPerson x)team
<有没有办法创建更有效的匹配,所以我不需要检查每件衣服的情况?就像这样:
让matchPerson person =
与
匹配的人| Person(姓名,_(丑陋,_)) - > printfn%s穿着丑陋的东西。名称
| _ - > ()
当然,这是不正确的语法。但是,我怎样才能达到这样的效果呢? 解决方案
这并不简单,你可以使用反射,但问题在于你的歧视工会需要一些重新设计,因为如果你知道总会有一个ClothingProperties,那么你可以改变它:
type Style =尼斯|酷|丑陋的
type Color = Blue |黄色|橙色|灰色|青色
类型ClothingProperties =风格*颜色//或者只是使用元组
类型衣物=
|牛仔裤
|套头衫
|衬衫
类型衣服=衣物*衣服物业
类型人物=
|字符串的人*衣服
让matchPerson人=
与
匹配的人| Person(姓名,(_,(Ugly,_))) - > printfn%s穿着丑陋的东西。名称
| _ - > ()
相关的问题在这里描述是否有可能将歧视联合标签作为参数传递?
In the following real world example I do a match:
type Style = Nice | Cool | Ugly
type Color = Blue | Yellow | Orange | Grey | Cyan
type ClothingProperties = Style * Color
type Clothes =
| Jeans of ClothingProperties
| Pullover of ClothingProperties
| Shirt of ClothingProperties
type Person =
| Person of string * Clothes
let team = [Person("Jan", Jeans (Cool, Blue)); Person("Pete", Shirt (Nice, Cyan)); Person("Harry", Pullover (Ugly, Grey))]
let matchPerson person=
match person with
| Person(name, Jeans(Ugly,_) ) -> printfn "%s wears ugly stuff." name
| Person(name, Pullover(Ugly,_) ) -> printfn "%s wears ugly stuff." name
| Person(name, Shirt(Ugly,_) ) -> printfn "%s wears ugly stuff." name
| _ -> ()
List.iter(fun x->matchPerson x) team
Is there a way to create a more efficient match, so I don't need to check each clothing case? Something like this:
let matchPerson person=
match person with
| Person(name, _ (Ugly,_) ) -> printfn "%s wears ugly stuff." name
| _ -> ()
Of course, this is not correct syntax. But how can I achieve such an effect?
That's not straightforward, you can use reflection, but the problem is that your discriminated union needs some redesign, because if you know there will always be a ClothingProperties then you can change it to this:
type Style = Nice | Cool | Ugly
type Color = Blue | Yellow | Orange | Grey | Cyan
type ClothingProperties = Style * Color // or just use a tuple
type Clothe =
| Jeans
| Pullover
| Shirt
type Clothes = Clothe *ClothingProperties
type Person =
| Person of string * Clothes
let matchPerson person=
match person with
| Person(name, (_,(Ugly,_)) ) -> printfn "%s wears ugly stuff." name
| _ -> ()
A related issue is described here Is it possible to pass discriminated union tags as arguments?
这篇关于通配符用于匹配歧视联盟时的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!