我正在寻找一种技术,该技术允许在对之前的列表的后续折叠调用之间进行记忆。
我看过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
时间表明折痕是从头算起的。有没有办法使后续的折叠重用以前的折叠结果?
答案 0 :(得分:2)
输入数据类型!
>>> float('NaN')
nan
>>> type(float('NaN'))
<class 'float'>
请注意,会导出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
函数(通常称为“智能构造函数”。