naw*_*fal 1 f# pattern-matching
刚开始玩F#.虽然现在和我一样可怕,但我也不知道要搜索类似的线程.
这就是我想要做的:
let test animal =
if animal :? Cat //testing for type
then "cat"
elif animal :? Dog //testing for type
then "dog"
elif animal = unicorn //testing value equality
then "impossible"
else "who cares"
Run Code Online (Sandbox Code Playgroud)
基本上它涉及类型测试模式匹配以及其他条件检查.我可以像这样完成第一部分(类型检查):
let test(animal:Animal) =
match animal with
| :? Cat as cat -> "cat"
| :? Dog as dog -> "cat"
| _ -> "who cares"
Run Code Online (Sandbox Code Playgroud)
1.我是否可以在上述类型测试模式匹配中包含相等性检查(如第一个示例中所示)?
2.在F#圈中,在单一模式匹配结构中执行的这种多种检查通常是不受欢迎的吗?
这是使用模式匹配的等价物:
let test (animal:Animal) =
match animal with
| :? Cat as cat -> "cat"
| :? Dog as dog -> "dog"
| _ when animal = unicorn -> "impossible"
| _ -> "who cares"
Run Code Online (Sandbox Code Playgroud)
我不会说这是不赞成的.它有时需要使用OOP,它已经比C#等价物更好(更简洁,更清晰).