gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:30:24 25 4
gpt4 key购买 nike

请注意以下类(class):

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

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

最佳答案

您可以使用 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 ...

关于haskell - 你如何为类型类方法编写重写规则?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32130011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com