列表在Clojure中有特殊地位,因为代码本身就是由列表构成的:
;; 列表会被求值为函数调用
(+ 1 2) ; => 3 (列表被求值为函数调用)
;; 向量不会被求值为函数调用
[+ 1 2] ; => [#<core$_PLUS_ clojure.core$_PLUS_@...> 1 2]
- 当需要表示代码或进行函数调用时,使用列表
- 当需要存储数据或频繁按索引访问时,使用向量
- 当需要频繁在头部添加元素时,使用列表
- 当需要频繁在尾部添加元素时,使用向量
One common need is an anonymous function that takes an element and wraps it in a vector. You might try writing that as:
<em>;; DO NOT DO THIS</em>
#([%])
This anonymous function expands to the equivalent:
(fn [x] ([x]))
This form will wrap in a vector and try to invoke the vector with no arguments (the extra pair of parentheses). Instead:
<em>;; Instead do this:</em>
#(vector %)
<em>;; or this:</em>
(fn [x] [x])
<em>;; or most simply just the vector function itself:</em>
vector