Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Canonical way to test data types [duplicate]

Tags:

haskell

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 image 925
daydaynatation Avatar asked Mar 01 '23 16:03

daydaynatation


1 Answers

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.

like image 107
leftaroundabout Avatar answered Mar 06 '23 16:03

leftaroundabout