为什么不将输入和输出上具有相同数据结构(相同暗淡)的组合自递归函数与其他递归内联在一起?
在教程 https://markkarpov.com/ tutorial/ghc-optimization-and-fusion.html#fusion-without-rewrite-rules 是一个代码示例,不会通过 fusion 进行优化。
map0 :: (a -> b) -> [a] -> [b]
map0 _ [] = []
map0 f (x:xs) = f x : map0 f xs
foldr0 :: (a -> b -> b) -> b -> [a] -> b
foldr0 _ b [] = b
foldr0 f b (a:as) = foldr0 f (f a b) as
nofusion0 :: [Int] -> Int
nofusion0 = foldr0 (+) 0 . map0 sqr
sqr :: Int -> Int
sqr x = x * x
我的问题是:为什么不是 function foldr0 (+) 0 。如果编译器可以轻松证明,map0 不会更改数据结构维度并推断出从结构向上到结构向下的所有内容,map0 sqr 会自动内联到一个递归中?我还是不明白,为什么这种代码在不重写规则的情况下不能自动优化。
您知道为什么不使用此优化的具体原因吗?
谢谢。
In tutorial https://markkarpov.com/tutorial/ghc-optimization-and-fusion.html#fusion-without-rewrite-rules is a code example, which will not be optimized by fusion.
map0 :: (a -> b) -> [a] -> [b]
map0 _ [] = []
map0 f (x:xs) = f x : map0 f xs
foldr0 :: (a -> b -> b) -> b -> [a] -> b
foldr0 _ b [] = b
foldr0 f b (a:as) = foldr0 f (f a b) as
nofusion0 :: [Int] -> Int
nofusion0 = foldr0 (+) 0 . map0 sqr
sqr :: Int -> Int
sqr x = x * x
My question is: Why isn't function foldr0 (+) 0 . map0 sqr
automatically inlined together into one recursion if the compiler can easily prove, that map0 doesn't change data structure dimension and deduce everything on run from the up of structure to the down of structure? I can't still find out, why this kind of code can't be automatically optimized without rewritting rules.
Do you know any specific reason, why this optimization isn't used please?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为可以优化您的示例的最有前途的方法称为超级编译。有一篇关于惰性函数式语言的超级编译的论文:https: //www.microsoft.com/en-us/research/publication/supercompilation-by-evaluation/。
在论文的未来工作部分,作者指出:
已经有人尝试将超级编译集成到 GHC 中,但尚未成功。我不知道所有细节,但有一个非常技术性的 GHC wiki 页面: https://gitlab.haskell.org/ghc/ghc/-/wikis/supercompilation。
I think the most promising approach that could optimize your example is called supercompilation. There is a paper about supercompilation for lazy functional languages: https://www.microsoft.com/en-us/research/publication/supercompilation-by-evaluation/.
In the future work section of the paper the authors state:
There has been work on trying to integrate supercompilation into GHC, but it has not yet been successful. I don't know all the details, but there is a very technical GHC wiki page about it: https://gitlab.haskell.org/ghc/ghc/-/wikis/supercompilation.