How to perform multiple styles of pattern matching?

╄→гoц情女王★ 提交于 2020-01-16 01:09:07

问题


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.

This is what I'm trying to do:

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. 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. Is such multiple kinds of checks performed in a single pattern matching construct generally frowned upon in F# circle?


回答1:


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"

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.



来源:https://stackoverflow.com/questions/16679503/how-to-perform-multiple-styles-of-pattern-matching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!