import Data.Typeable(typeOf)
myFunc :: (Show a) => [a] -> [String]
myFunc
| show (typeOf a) == "[Char]" = ...
| otherwise = ..
I use the above code to test if the input is of the String
type.
Is this correct and acceptable or are there other better ways?
Like with matching values, we prefer to avoid using booleans altogether. In context of typeable/dynamic, this means you shouldn't “test” whether it is some particular type and then do something if it is, but instead (like with value pattern-matching) you simply try to use it as that type, and then add fallback cases just for when that fails.
myFunc' :: (Show a, Typeable a) => a -> String
myFunc' x = case cast x of
Just xStr -> xStr
_ -> show x
Note that I don't even need to mention that xStr
handles the case where x
is String
, because that is already implied by the context.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With