Reputation: 73163
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?
Upvotes: 1
Views: 215
Reputation: 47904
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.
Upvotes: 5