Using ViewPatterns
and Data.Typeable
,我成功地编写了一个函数,允许我编写类似于类型案例分析的内容。观察:
{-# LANGUAGE GADTs, PatternSynonyms, RankNTypes, ScopedTypeVariables
, TypeApplications, TypeOperators, ViewPatterns #-}
import Data.Typeable
viewEqT :: forall b a. (Typeable a, Typeable b) => a -> Maybe ((a :~: b), b)
viewEqT x = case eqT @a @b of
Just Refl -> Just (Refl, x)
Nothing -> Nothing
evilId :: Typeable a => a -> a
evilId (viewEqT @Int -> Just (Refl, n)) = n + 1
evilId (viewEqT @String -> Just (Refl, str)) = reverse str
evilId x = x
以上evilId
事实上,函数非常邪恶,因为它使用了Typeable
彻底颠覆参数化:
ghci> evilId True
True
ghci> evilId "hello"
"olleh"
由于我喜欢作恶,所以我对此感到非常满意,但是上面的语法非常嘈杂。我希望能够更清楚地编写相同的代码,因此我决定编写一个模式同义词:
pattern EqT :: forall b a. (Typeable a, Typeable b) => (a ~ b) => b -> a
pattern EqT x <- (viewEqT @b -> Just (Refl, x))
我想我可以使用这个模式同义词来使我的邪恶案例分析更容易阅读:
evilId :: Typeable a => a -> a
evilId (EqT (n :: Int)) = n + 1
evilId (EqT (str :: String)) = reverse str
evilId x = x
可悲的是,这根本不起作用。 GHC 在对模式进行类型检查之前似乎没有查阅我的类型注释,因此它认为b
是每个模式中的不明确变量。有什么方法可以用模式同义词干净地包装这些模式,或者我会坚持我的较长视图模式吗?