sequence定义
sequence不是一般的list,实际上实现了ISeq接口,ISeq接口定义如下:
[java]
package clojure.lang;
/**
* A persistent, functional, sequence interface
*
* ISeqs are immutable values, i.e. neither first(), nor rest() changes
* or invalidates the ISeq
*/
public interface ISeq extends IPersistentCollection, Sequential{
Object first();
ISeq next();
ISeq more();
ISeq cons(Object o);
}
sequence的操作
参考官方文档的说明:
[plain]
The Seq interface
(first coll)
Returns the first item in the collection. Calls seq on its argument. If coll is nil, returns nil.
(rest coll)
Returns a sequence of the items after the first. Calls seq on its argument. If there are no more items, returns a logical sequence for which seq returns nil.
(cons item seq)
Returns a new seq where item is the first element and seq is the rest.
下面的操作定义了一个sequence, 然后返回第一个元素。
[plain]
user=> (first (map #(print-str %) [1 2 3]))
"1"
返回除了第一元素之外的其余元素组成的列表:
[plain]
user=> (rest (map #(print-str %) [1 2 3]))
("2" "3")
注意,#(print-str %) 函数将元素转变成了字符串。
lazy sequence
只有当sequence真正被使用的时候,才会被真正填充元素。这叫做lazy sequence。前面的(map实际上返回的就是lazy sequence。只有当调用first的时候才获得包含真正数据的sequence。
script和REPL的区别
不过在REPL会话环境下,lazy sequence是无效的,因为REPL会强制填充sequence,并返回。只是为了方便你看到。
xml-seq
现在回到前面一篇使用的xml
http://blog.csdn.net/sheismylife/article/details/8444290
xml-seq可以返回lazy sequence
[plain]
user=> (require 'clojure.xml)
nil
user=> (use 'clojure.xml)
nil
user=> (parse "/home/chenshu/a.xml")
{:tag :service, :attrs nil, :content [{:tag :mongodb, :attrs nil, :content [{:tag :uri, :attrs nil, :content ["localhost"]}]} {:tag :socket, :attrs nil, :content [{:tag :port_number, :attrs nil, :content ["7777"]} {:tag :login_timeout, :attrs nil, :content ["200"]} {:tag :check_timeout, :attrs nil, :content ["200"]}]}]}
user=> (xml-seq (parse "/home/chenshu/a.xml"))
({:tag :service, :attrs nil, :content [{:tag :mongodb, :attrs nil, :content [{:tag :uri, :attrs nil, :content ["localhost"]}]} {:tag :socket, :attrs nil, :content [{:tag :port_number, :attrs nil, :content ["7777"]} {:tag :login_timeout, :attrs nil, :content ["200"]} {:tag :check_timeout, :attrs nil, :content ["200"]}]}]} {:tag :mongodb, :attrs nil, :content [{:tag :uri, :attrs nil, :content ["localhost"]}]} {:tag :uri, :attrs nil, :content ["localhost"]} "localhost" {:tag :socket, :attrs nil, :content [{:tag :port_number, :attrs nil, :content ["7777"]} {:tag :login_timeout, :attrs nil, :content ["200"]} {:tag :check_timeout, :attrs nil, :content ["200"]}]} {:tag :port_number, :attrs nil, :content ["7777"]} "7777" {:tag :login_timeout, :attrs nil, :content ["200"]} "200" {:tag :check_timeout, :attrs nil, :content ["200"]} "200")
user=>
格式化一下,再看:
[plain]
(
{:tag :service, :attrs nil, :content [{:tag :mongodb, :attrs nil, :content [{:tag :uri, :attrs nil, :content ["localhost"]}]}
{:tag :socket, :attrs nil, :content [{:tag :port_number, :attrs nil, :content ["7777"]}
{:tag :login_timeout, :attrs nil, :content ["200"]}
{:tag :check_timeout, :attrs nil, :content