我很难理解Haskell懒惰的评价。
我编写了简单的测试程序。它读取4行数据
第二和第四输入线具有许多数字。
consumeList :: [Int] -> [Int] -> [Int]
consumeList [] _ = error "hi" -- to generate heap debug
consumeList (x:xs) y = consumeList xs y
main = do
inputdata <- getContents
let (x:y:z:k:xs) = lines inputdata
s = map (read ::String->Int) $ words $ k
t = []
print $ consumeList s t
words
和
map
已执行
对于懒散的字符流,这个程序使用恒定的内存。
但当我添加论点时
t
,情况发生了变化。
我的期望是
t型
是
地图
和
话
在懒流上,
和
t型
未用于
consumeList
,此更改不应更改
内存使用情况。但没有。
consumeList :: [Int] -> [Int] -> [Int]
consumeList [] _ = error "hi" -- to generate heap debug
consumeList (x:xs) y = consumeList xs y
main = do
inputdata <- getContents
let (x:y:z:k:xs) = lines inputdata
s = map (read ::String->Int) $ words $ k
t = map (read ::String->Int) $ words $ y
print $ consumeList s t -- <-- t is not used
Q1)为什么当
t型
根本不使用?
我还有一个问题。当我模式匹配懒惰流时
[,]
不
具有
(:)
存储器分配行为被改变。
consumeList :: [Int] -> [Int] -> [Int]
consumeList [] _ = error "hi" -- to generate heap debug
consumeList (x:xs) y = consumeList xs y
main = do
inputdata <- getContents
let [x,y,z,k] = lines inputdata -- <---- changed from (x:y:..)
s = map (read ::String->Int) $ words $ k
t = []
print $ consumeList s t
Q2)是
(:)
和
[,]
在懒惰评估方面有所不同?
欢迎任何评论。谢谢
[编辑]
Q3)那么,是否可以先处理第四条生产线
处理第二行,而不增加内存消耗?
德里克指导的实验如下。
通过从第二个例子中切换y和k,我得到了相同的结果:
consumeList :: [Int] -> [Int] -> [Int]
consumeList [] _ = error "hi"
consumeList (x:xs) y = consumeList xs y
main = do
inputdata <- getContents
let (x:y:z:k:xs) = lines inputdata
s = map (read ::String->Int) $ words $ y -- <- swap with k
t = map (read ::String->Int) $ words $ k -- <- swap with y
print $ consumeList s t