你如何为类型类方法编写重写规则?

时间:2015-08-20 23:21:33

标签: haskell optimization ghc

请注意以下课程:

class ListIsomorphic l where
    toList    :: l a -> [a]
    fromList  :: [a] -> l a

我还要求toList . fromList == id。如何编写重写规则来告诉GHC进行替换?

1 个答案:

答案 0 :(得分:10)

您可以使用RULES pragma来实现此简化,但您必须执行a bit of extra work以确保通用方法重写规则在您的机会有效之前不会触发:

{-# RULES
  "protect toList"   toList = toList';
  "protect fromList" fromList = fromList';
  "fromList/toList"  forall x . fromList' (toList' x) = x; #-}

{-# NOINLINE [0] fromList' #-}
fromList' :: (ListIsomorphic l) => [a] -> l a
fromList' = fromList

{-# NOINLINE [0] toList' #-}
toList' :: (ListIsomorphic l) => l a -> [a]
toList' = toList

这是一个愚蠢的例子,表明它有效:

instance ListIsomorphic Maybe where
    toList = error "toList"
    fromList = error "fromList"

test1 :: Maybe a -> Maybe a
test1 x = fromList (toList x)

main = print $ test1 $ Just "Hello"

这会打印Just "Hello"而不是错误输出。此外,您可以看到规则触发:

$ ghc -O -ddump-rule-firings --make rewrite-method.hs
[1 of 1] Compiling Main             ( rewrite-method.hs, rewrite-method.o )
Rule fired: protect toList
Rule fired: protect fromList
Rule fired: unpack
Rule fired: unpack
Rule fired: protect toList
Rule fired: protect fromList
Rule fired: fromList/toList
Rule fired: unpack
Rule fired: Class op show
Rule fired: >#
Rule fired: tagToEnum#
Rule fired: Class op showsPrec
Rule fired: Class op showList
Rule fired: ++
Rule fired: unpack-list
Rule fired: foldr/app
Rule fired: unpack-list
Rule fired: unpack-list
Linking rewrite-method.exe ...