The way that Haskell is designed is very much opposed to the concept of an instanceof
check. Haskell's design does not incorporate this sort of runtime type check, because Haskell is very focused on strong compilation-time guarantees: a function should not be able to learn the type of its arguments at runtime any more precisely than it knows them at compilation time.
This doesn't meant that the feature doesn't exist in Haskell—Lee's answer demonstrates how to do it—but in Haskell this is an opt-in feature provided by a library, not a core part of the language (unlike a language like Java, where it's a core feature that's always present—you can't opt out of it!).
Note that even in object-oriented programming the instanceof
operator is controversial. Many object-oriented programmers very strongly advise against its use. A few examples (out of hundreds):
The advise in all of these tends to be the same: instead of using testing the type of a reference and switching to different behaviors based on it, use polymorphism: define an interface or class that has a method for the operation you want, and have the objects that you were testing with instanceof
implement their own versions of that method to do the right thing.
This advice can be translated straightforwardly to Haskell:
- Define your own type class to represent the behavior you want
- Implement this type class for each of the types that you're interested in, with the correct behavior for each.
So, you could do something like this:
class ToString a where
toString :: a -> String
instance ToString String where
toString str = str
instance ToString Integer where
toString i = show i
-- ...