![](/img/trans.png)
[英]How do I use if/then/else or guards in a case statement in Haskell?
[英]In Haskell, how to do a case statement on Dynamic TypeRef
我嘗試了以下方法:
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"
但它警告重疊模式匹配並且不能正常工作。 它始終是第一個模式而不是正確模式。
case
表達式中->
的左側是模式 ,而不是表達式 。 模式stringType
將匹配任何內容並將本地名稱stringType
綁定到它。 它不會比較平等。
編譯器告訴你你的模式intType
和_
永遠不會到達; 由於stringType
模式首先出現並匹配任何內容,因此將始終選擇其右側。
正如Claudiu建議的那樣,你會想要使用警衛。 像這樣的東西應該做的伎倆:
dynFunc d | rep == stringType = ...
| rep == intType = ...
| otherwise = error ...
where rep = dynTypeRep d
如果您有很多可能性,您可能需要考慮制作一個列表並使用lookup
功能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.