将文件读入列表,每个元素代表文件的一行
在 clojure 中,如何将文件读入序列,其中每一行都是序列中的一个元素。所以我想看看函数 get-lines
的定义,这样我就可以执行以下操作:
(def lines (get-lines "test.txt"))
lines 是一个非惰性序列。
In clojure, how do I read a file into a sequence where each line is one element in the sequence. So I'd like to see the definition of the function get-lines
so I could do the following:
(def lines (get-lines "test.txt"))
and lines is a non-lazy sequence.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
替代实现:
此函数返回结果向量而不是 seq。
如果您不使用 1.3,则需要 clojure.contrib.string。
Alternate implementation:
This function returns a vector of the results instead of a seq.
If you are not using 1.3, require clojure.contrib.string instead.
要将惰性序列转换为非惰性序列,您可以使用
doall
,如下所示:To convert lazy sequence to non-lazy you can use
doall
like so:您可以使用
line-seq
。一个简单的例子:
请注意,
line-seq
是惰性。您必须小心,不要在阅读器关闭后消耗序列。以下内容将不起作用:第一个示例之所以有效,是因为
count
不是惰性的。如果你想用这些行做一些事情(有副作用),你可能会发现
doseq
最有用:You could use
line-seq
. A quick example:Note that
line-seq
is lazy. You must be careful not to consume the sequence after the reader is closed. The following will not work:The first example works because
count
isn't lazy.If you want to do something (with side effects) with the lines you'll probably find
doseq
most useful: