为什么不将输入和输出上具有相同数据结构(相同暗淡)的组合自递归函数与其他递归内联在一起?

发布于 2025-01-09 02:25:49 字数 795 浏览 7 评论 0原文

在教程 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

野心澎湃 2025-01-16 02:25:49

我认为可以优化您的示例的最有前途的方法称为超级编译。有一篇关于惰性函数式语言的超级编译的论文: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:

The major barriers to the use of supercompilation in practice are code bloat and compilation time.

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文