Jan*_*gel 3 f# functional-programming pattern-matching discriminated-union
在下面的真实世界的例子中我做了一个匹配:
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
Run Code Online (Sandbox Code Playgroud)
有没有办法创造一个更有效的比赛,所以我不需要检查每个服装案例?像这样的东西:
let matchPerson person=
match person with
| Person(name, _ (Ugly,_) ) -> printfn "%s wears ugly stuff." name
| _ -> ()
Run Code Online (Sandbox Code Playgroud)
当然,这不是正确的语法.但是我怎样才能达到这样的效果呢?
这不是直截了当的,你可以使用反射,但问题是你的歧视联盟需要一些重新设计,因为如果你知道总会有一个ClothingProperties然后你可以改为:
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
| _ -> ()
Run Code Online (Sandbox Code Playgroud)
这里描述了一个相关的问题是否可以将区分的联合标记作为参数传递?