line-seq的行为是什么? [英] What will the behaviour of line-seq be?

查看:91
本文介绍了line-seq的行为是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用doseq进行迭代,但要保留第一个元素的一部分,我想了解惰性序列的行为.

I'd like to understand the behaviour of a lazy sequence if I iterate over with doseq but hold onto part of the first element.

 (with-open [log-file-reader (clojure.java.io/reader (clojure.java.io/file input-file-path))]

    ; Parse line parse-line returns some kind of representation of the line.
    (let [parsed-lines (map parse-line (line-seq log-file-reader))
          first-item (first parsed-lines)]

          ; Iterate over the parsed lines
          (doseq [line parsed-lines]
            ; Do something with a side-effect  
          )))

我不想保留任何列表,我只想对每个元素执行一个副作用.我相信没有first-item就不会有问题.

I don't want to retain any of the list, I just want to perform a side-effect with each element. I believe that without the first-item there would be no problem.

我的程序中有内存问题,我认为也许在parsed-line序列的开头保留对某些内容的引用就意味着整个序列都已存储.

I'm having memory issues in my program and I think that perhaps retaining a reference to something at the start of the parsed-line sequence means that the whole sequence is stored.

这里定义的行为是什么?如果要存储序列,是否有通用的方法来复制对象并允许对序列的已实现部分进行垃圾回收?

What's the defined behaviour here? If the sequence is being stored, is there a generic way to take a copy of an object and enable the realised portion of the sequence to be garbage collected?

推荐答案

序列保持在此处发生

...
(let [parsed-lines (map parse-line (line-seq log-file-reader))
...

文件中的行序列被延迟生成和解析,但是整个序列都保留在let的范围内.该序列在doseq中实现,但是doseq并不是问题,它不执行序列保持.

The sequence of lines in the file are being lazily produce and parsed, but the entire sequence is held onto, within the scope of let. This sequence is realized in the doseq, but doseq is not the problem, it does not do sequence-holding.

...
(doseq [line parsed-lines]
 ; Do something
...

您不必关心let中的序列保持,因为let的范围是有限的,但是在这里假定您的文件很大和/或您在let的动态范围内同时,或者返回做某事"部分中包含它的闭包.

You wouldn't necessarily care about sequence-holding in a let because the scope of let is limited, but here presumably your file is large and/or you stay within the dynamic scope of let for a while, or perhaps return a closure containing it in the "do something" section.

请注意,保留序列的任何给定元素(包括第一个元素)都不会保留该序列.如果您认为head是Prolog中列表中的头"中的第一个元素,那么头保留一词有点用词不当.问题在于对序列的引用.

Note that holding onto any given element of the sequence, including the first, does not hold the sequence. The term head-holding is a bit of a misnomer if you consider head to be the first element as in "head of the list" in Prolog. The problem is holding onto a reference to the sequence.

这篇关于line-seq的行为是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆