开发者

In Haskell, how to do a case statement on Dynamic TypeRef

开发者 https://www.devze.com 2023-04-04 02:05 出处:网络
I tried the following: intType =typeOf (5::Int) stringType = typeOf \"s\" dynFunc :: Dynamic -> IO ()

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 a case expression are patterns, not expressions. The pattern stringType will match anything and bind the local name stringType to it. It will not compare for equality.

The compiler is telling you that your patterns intType and _ will never be reached; since the stringType pattern 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:

dynFunc d | rep == stringType = ...
          | rep == intType    = ...
          | otherwise         = error ...
          where rep = dynTypeRep d

If you have many possibilities, you might want to consider making a list and using the lookup function.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号