【问题标题】:Deforestation in a Hylomorphism类型中的森林砍伐
【发布时间】:2018-03-07 00:48:40
【问题描述】:

维基百科写到Hylomorphism

在 [...] 函数式编程中,hylomorphism 是递归的 函数,对应于变形的组合(其中 首先构建一组结果;也称为“展开”)随后 通过变态(然后将这些结果折叠成最终的回报 价值)。将这两个递归计算融合为一个 递归模式然后避免构建中间数据 结构。这是森林砍伐的一个例子,一个程序 优化策略。

(我的粗体标记)

使用recursion-schemes 库 我写了一个很简单的hylomorphism:

import Data.Functor.Foldable
main :: IO ()
main = putStrLn $ show $ hylosum 1000

hylosum :: Int -> Int
hylosum end = hylo alg coalg 1
  where 
    -- Create list of Int's from 1 to n
    coalg :: Int -> ListF Int Int
    coalg n 
       | n > end = Nil
       | otherwise = Cons n (n + 1)
    -- Sum up a list of Int's
    alg :: ListF Int Int -> Int
    alg Nil  =  0
    alg (Cons a x) = a + x

在 cabal 文件中我指示 GHC 优化代码:

name:                Hylo
version:             0.1.0.0
synopsis:            Hylomorphisms and Deforestation        
build-type:          Simple
cabal-version:       >=1.10

executable             Hylo
  main-is:             Main.hs
  ghc-options:         -O2
  build-depends:       base >=4.10 && <4.11 , recursion-schemes      
  default-language:    Haskell2010

使用堆栈 lts-10.0 (GHC 8.2.2) 我使用 stack build 编译并使用 stack exec Hylo -- +RTS -s 运行,我得到:

500500
      84,016 bytes allocated in the heap
       3,408 bytes copied during GC
      44,504 bytes maximum residency (1 sample(s))
      25,128 bytes maximum slop
           2 MB total memory in use (0 MB lost due to fragmentation)

现在我将hylosum 1000 更改为hylosum 1000000(1000 倍以上),我得到:

500000500000
  16,664,864 bytes allocated in the heap
      16,928 bytes copied during GC
  15,756,232 bytes maximum residency (4 sample(s))
      29,224 bytes maximum slop
          18 MB total memory in use (0 MB lost due to fragmentation)

因此堆使用量从 84 KB 上升到 16,664 KB。这比以前多了200倍。 因此我认为,GHC 不会做维基百科中提到的森林砍伐/融合!

这并不奇怪:变形从左到右创建列表项 (从 1 到 n)并且 catamorphism 从右到左以相反的方式消耗物品 (从 n 到 1)并且很难看出 hylomorphism 是如何工作的 无需创建整个中间列表。

问题: GHC 是否能够执行森林砍伐? 如果,我需要在我的代码或 cabal 文件中进行哪些更改? 如果,它是如何真正起作用的? 如果,问题出在哪里:维基百科、GHC 还是图书馆?

【问题讨论】:

标签: haskell ghc recursion-schemes


【解决方案1】:

数据结构实际上被融合掉了,但是生成的程序不是尾递归的。优化后的代码基本上是这样的(看不到ConsNil):

h n | n > end = 0
    | otherwise = n + h (n+1)

要评估结果,您必须首先递归地评估h (n+1),然后将结果添加到n。在递归调用期间,值n 必须保持存储在某处,因此我们观察到随着end 的增加内存使用量增加。

通过将递归调用置于尾部位置并携带一个恒定大小的累加器,可以获得更紧密的循环。我们希望代码对此进行优化:

-- with BangPatterns
h n !acc | n > end = acc
         | otherwise = h (n+1) (n + acc)

hylosum 中,对(+) 的调用发生在alg 中,我们将其替换为对将由hylo 构建的延续的调用。

alg :: ListF Int (Int -> Int) -> Int -> Int
alg Nil acc = acc
alg (Cons n go) !acc = go (n + acc)

我看到堆中分配了一个常量 51kB。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-02
    • 2019-12-06
    • 2020-11-16
    • 1970-01-01
    • 2021-12-22
    • 2017-03-15
    • 2020-02-25
    • 2018-07-10
    相关资源
    最近更新 更多