如何执行多种样式的模式匹配? [英] How to perform multiple styles of pattern matching?

查看:65
本文介绍了如何执行多种样式的模式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚开始玩F#.就像我现在所经历的那样可怕,我也不知道也要搜索类似的线程.

Just started to play with F#. As terrible as I'm with it now, I do not to know to search for a similar thread too.

这就是我想要做的:

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"

基本上,它涉及类型测试模式匹配以及其他条件检查.我可以像这样完成第一部分(类型检查):

Basically it involves type test pattern matching along with other conditional checks. I can get the first part (type checking) done like this:

let test(animal:Animal) =
    match animal with
    | :? Cat as cat -> "cat"
    | :? Dog as dog -> "cat"
    | _ -> "who cares"

1..是否有一种方法可以将相等性检查(如第一个示例中一样)以及上述类型测试模式匹配中并入?

1. Is there a way I can incorporate the equality checking (as in the first example) as well in the above type test pattern matching?

2..通常在F#圈子中是否会在单一模式匹配结构中执行这种多种检查?

2. Is such multiple kinds of checks performed in a single pattern matching construct generally frowned upon in F# circle?

推荐答案

这与使用模式匹配等效:

This is the equivalent using pattern matching:

let test (animal:Animal) =
  match animal with
  | :? Cat as cat -> "cat"
  | :? Dog as dog -> "dog"
  | _ when animal = unicorn -> "impossible"
  | _ -> "who cares"

我不会说这是不合时宜的. OOP有时需要使用它,并且它已经比C#等效语言更好(更简洁,更清晰).

I wouldn't say this is frowned upon. It's sometimes needed with OOP and it's already better (more concise, clearer) than the C# equivalent.

这篇关于如何执行多种样式的模式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆