简体   繁体   English

如何改进此Clojure功能?

[英]How can I improve this Clojure function?

I just wrote my first Clojure function based on my very limited knowledge of the language. 我刚刚根据我对语言的非常有限的知识编写了我的第一个Clojure函数。 I would love some feedback in regards to performance and use of types. 我希望得到一些关于性能和类型使用的反馈。 For example, I'm not sure if I should be using lists or vectors. 例如,我不确定我是否应该使用列表或向量。

(defn actor-ids-for-subject-id [subject-id]
  (sql/with-connection (System/getenv "DATABASE_URL")
    (sql/with-query-results results
      ["SELECT actor_id FROM entries WHERE subject_id = ?" subject-id]
      (let [res (into [] results)]
        (map (fn [row] (get row :actor_id)) res)))))

It passes the following test (given proper seed data): 它通过以下测试(给出适当的种子数据):

(deftest test-actor-ids-for-subject-id
  (is (= ["123" "321"] (actor-ids-for-subject-id "123"))))

If it makes a difference (and I imagine it does) my usage characteristics of the returned data will almost exclusively involve generating the union and intersection of another set returned by the same function. 如果它有所不同(我想它确实如此),我返回数据的使用特性几乎只涉及生成由同一函数返回的另一个集合的并集和交集。

it's slightly more concise to use 'vec' instead of 'into' when the initial vector is empty. 当初始向量为空时,使用'vec'而不是'into'会稍微简洁一些。 it may express the intent more clearly, though that's more a matter of preference. 它可以更清楚地表达意图,尽管这更多的是偏好问题。

(vec (map :actor_id results))

the results is a clojure.lang.Cons , is lazy sequence, return by clojure.java.jdbc/resultset-seq . results是一个clojure.lang.Cons ,是懒惰的序列,由clojure.java.jdbc/resultset-seq返回。 each record is a map : 每条记录都是一张map

(defn actor-ids-for-subject-id [subject-id]
  (sql/with-connection (System/getenv "DATABASE_URL")
    (sql/with-query-results results
      ["SELECT actor_id FROM entries WHERE subject_id = ?" subject-id]
      (into [] (map :actor_id results)))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM