19

My first F# day. If I have this:

let cat = Animal()

Now how do I check at later stage if cat is Animal?

In C#

bool b = cat is Animal;

In F#?

dreftymac
  • 31,404
  • 26
  • 119
  • 182
nawfal
  • 70,104
  • 56
  • 326
  • 368

3 Answers3

28

@ildjarn deserves the credit here for answering first, but I'm submitting the answer here so it can be accepted.

The F# equivalent of the C# is keyword is :?. For example:

let cat = Animal()
if cat :? Animal then
    printfn "cat is an animal."
else
    printfn "cat is not an animal."
Jack P.
  • 11,487
  • 1
  • 29
  • 34
9

For demonstration only (don't define an is function):

let is<'T> (x: obj) = x :? 'T

type Animal() = class end
type Cat() = inherit Animal()

let cat = Cat()
cat |> is<Animal> //true
Daniel
  • 47,404
  • 11
  • 101
  • 179
  • Daniel, can you tell me what is `|>` ? Why should one include it before a function call? Does it have a name? – nawfal May 21 '13 at 19:54
  • 3
    It's called the forward pipe operator. It applies the operand on the left as the last argument to the function on the right. ([see MSDN](http://msdn.microsoft.com/en-us/library/ee340273.aspx)) – Daniel May 21 '13 at 20:11
  • Daniel, why wouldn't you define is as a function, looks pretty useful to me? – sacha barber Dec 17 '14 at 15:55
  • 2
    @sacha: Given that there's a built-in type test operator (`:?`), `is<'T>` doesn't provide much value. Compare `cat is` to `cat :? Animal`. – Daniel Dec 17 '14 at 16:16
  • @Daniel : Yeah I guess, I think Is reads better personally, but I guess once you are familiar with all the weird FSharp operators, its fine. – sacha barber Dec 18 '14 at 08:48
  • 2
    You're right. It requires translation, i.e., reading `:?` as "is"—much the same as reading `>` as "greater than." – Daniel Dec 18 '14 at 16:55
4

I know I'm late. If you try to test the type of a collection in fsi with :? it will give an error, if the item types do not match. E.g.

let squares = seq { for x in 1 .. 15 -> x * x }  
squares :? list<int> ;;   // will give false  
squares :? list<string> ;; // error FS0193: Type constraint mismatch

Wrapping in a function like Daniels is<'T> works.

gfr_gfr
  • 41
  • 2