Clojure:如何让函数返回独立向量而非列表包裹的向量?
几种实现方案
下面是让函数返回可直接在clerk/html表格中使用的行元素的不同方法:
1. 用doall强制惰性序列求值
原for推导式返回惰性序列,doall会把它转为非惰性列表,确保clerk/html能正确展开每个行元素:
(defn destruct-cart-items [my-cart] (doall (for [[user product stock-amount] my-cart] [:tr [:td user] [:td product] [:td stock-amount]])))
2. 替换for为map
map同样能生成元素序列,逻辑和原函数一致,若担心惰性问题可搭配doall:
(defn destruct-cart-items [my-cart] (map (fn [[user product stock-amount]] [:tr [:td user] [:td product] [:td stock-amount]]) my-cart))
3. 用into转为向量集合
把for生成的序列直接收集到向量里,返回的向量包含所有行元素:
(defn destruct-cart-items [my-cart] (into [] (for [[user product stock-amount] my-cart] [:tr [:td user] [:td product] [:td stock-amount]])))
4. 利用for的:into参数
Clojure的for支持:into选项,可直接指定结果的集合类型,这里用向量:
(defn destruct-cart-items [my-cart] (for [[user product stock-amount] my-cart :into []] [:tr [:td user] [:td product] [:td stock-amount]]))
5. 不修改函数,在调用处拼接
如果不想改动原函数,可以在构建表格时用into把行元素直接合并到表格向量中:
(clerk/html (into [:table [:tr [:th "User"] [:th "Product"] [:th "Stock Amount"]]] (destruct-cart-items @!my-cart)))
内容的提问来源于stack exchange,提问作者Barış Can Ateş
相关产品推荐
相关产品推荐

