简体   繁体   English

在Haskell中,如何在Dynamic TypeRef上执行case语句

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

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 . case表达式中->的左侧是模式 ,而不是表达式 The pattern stringType will match anything and bind the local name stringType to it. 模式stringType将匹配任何内容并将本地名称stringType绑定到它。 It will not compare for equality. 不会比较平等。

The compiler is telling you that your patterns intType and _ will never be reached; 编译器告诉你你的模式intType_永远不会到达; since the stringType pattern comes first and matches anything, its right hand side will always be chosen. 由于stringType模式首先出现并匹配任何内容,因此将始终选择其右侧。

As Claudiu suggested, you'll want to use guards instead. 正如Claudiu建议的那样,你会想要使用警卫。 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. 如果您有很多可能性,您可能需要考虑制作一个列表并使用lookup功能。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM