Question

since Haskell has such expressive type system, is there something supported directly that we can query whether some data is of some type? like in Racket, (String? "Hi") (will return true) or like MyType? somedata -> Bool

Was it helpful?

Solution

isInt :: Int -> Bool
isInt _ = True

isString :: String -> Bool
isString _ = True

...

OTHER TIPS

In general, strong typing means you don't get into that kind of situation to start with; you always know the type you've been given, or you know nothing about it but have a dictionary of supported functions (typeclass instances). GHC does have Data.Typeable for when you're playing dirty tricks with the type system to get generic types, though.

Essentially, your question doesn't make sense in Haskell.

Haskell knows the type of everything statically -- at compile time. So there is no notion of "testing for a type" -- which would be a dynamic test. In fact, GHC erases all type information, since it is never needed at runtime.


The only exceptions to this would be cases where data is represented in a serialized format, such as a string. Then you use parsing as the way to test if a value has the correct type. Or, for advanced users, some type information may be required at runtime to resolve certain higher-order generic operations.

If you need to check for a type dynamically, then you've done something wrong. This is usually true in most languages with type reconstructors, so functional languages lik Haskell or OCaml or F#.

You have strong type reconstructor and pattern matching, why do you need to ask for a type?

In addition to the other answers...

You can, if you like, use the Data.Dynamic module to work with dynamic types in Haskell. For example:

> let dyns = [ toDyn (5 :: Int), toDyn "hello", toDyn not ]

Then you can easily write a test for a specific type using fromDynamic:

isString :: Dynamic -> Bool
isString dyn = isJust (fromDynamic dyn :: Maybe String)

And you can apply that to any Dynamic value to determine if it contains a String:

> map isString dyns
[False,True,False]

So if you choose to use dynamic typing using the Data.Dynamic module, then yes you can do this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top