gpt4 book ai didi

haskell - 内存后续折叠调用

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

我正在寻找一种技术,该技术允许在针对预先添加的列表的后续折叠调用之间进行内存。

我查看了 memoize library 但这似乎不支持高阶函数的内存,折叠就是这种情况。

我还尝试了使用惰性评估结果图的技术,但无济于事。

这是简单的示例代码:

module Main where

import Data.Time

printAndMeasureTime :: Show a => a -> IO ()
printAndMeasureTime a = do
startTime <- getCurrentTime
print a
stopTime <- getCurrentTime
putStrLn $ " in " ++ show (diffUTCTime stopTime startTime)

main = do
let as = replicate 10000000 1
printAndMeasureTime $ foldr (-) 0 as -- just to resolve thunks
printAndMeasureTime $ sum as
printAndMeasureTime $ sum (1:as) -- recomputed from scratch, could it reuse previous computation result?
printAndMeasureTime $ length (as)
printAndMeasureTime $ length (1:as) -- recomputed from scratch, could it reuse previous computation result?

和输出:
0
in 1.125098223s
10000000
in 0.096558168s
10000001
in 0.104047058s
10000000
in 0.037727126s
10000001
in 0.041266456s

时代表明折叠是从头开始计算的。有没有办法让后续的折叠重用以前的折叠结果?

最佳答案

制作数据类型!

module List (List, _elements, _sum, _length, toList, cons) where

data List = List
{ _elements :: [Int]
, _sum :: !Int
, _length :: !Int
}

toList :: [Int] -> List
toList xs = List xs (sum xs) (length xs)

cons :: Int -> List -> List
cons x (List xs t n) = List (x:xs) (x+t) (1+n)

请注意 List类型已导出,但 List构造函数不是,所以只有这样才能构造一个 List正在使用 toList函数(通常称为“智能构造函数”)。

关于haskell - 内存后续折叠调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51101391/

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