I tried the following:
intType = typeOf (5::Int)
stringType = typeOf "s"
dynFunc :: Dynamic -> IO ()
dynFunc d =
case dynTypeRep d of
stringType -> polyFunc ((fromDyn d "") :: String)
intType -> polyFunc ((fromDyn d 0) :: Int)
_ -> error "Could not coerce dynamic value"
But it warns of overlapping pattern matches and doesn’t work right. It always goes to first pattern instead of the correct one.
The left hand sides of the
->in acaseexpression are patterns, not expressions. The patternstringTypewill match anything and bind the local namestringTypeto it. It will not compare for equality.The compiler is telling you that your patterns
intTypeand_will never be reached; since thestringTypepattern comes first and matches anything, its right hand side will always be chosen.As Claudiu suggested, you’ll want to use guards instead. Something like this should do the trick:
If you have many possibilities, you might want to consider making a list and using the
lookupfunction.