You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用filter或for从哈希表向量中按ID提取作者姓名?

实现按ID提取作者姓名的函数

先优化你现有的谓词函数,其实不需要额外的if判断——比较表达式本身就会返回布尔值,精简后更符合Clojure风格:

(defn check-by-id [author id]
  (= id (:id author)))

方法一:使用filter实现

先通过filter筛选出匹配ID的作者,再提取姓名:

(def authors
  [{:id 100, :name "Albert Einstein", :interest "Physics"}
   {:id 200, :name "Alan Turing", :interest "Computer Science"}
   {:id 300, :name "Jeff Dean", :interest "Programming"}])

(defn get-author-name-by-id [target-id]
  (let [matched-authors (filter #(check-by-id % target-id) authors)]
    (map :name matched-authors)))

调用示例:

(get-author-name-by-id 200) ; => ("Alan Turing")

如果需要显式返回列表而非惰性序列,可以把最后一行改成:

(into '() (map :name matched-authors))

方法二:使用for推导实现

for推导可以一步完成筛选和提取逻辑,代码更紧凑:

(defn get-author-name-by-id [target-id]
  (for [author authors
        :when (check-by-id author target-id)]
    (:name author)))

调用示例:

(get-author-name-by-id 100) ; => ("Albert Einstein")

额外优化(ID唯一场景)

如果你的数据中作者ID是唯一的,用some可以直接定位到目标作者,效率更高,返回单个姓名而非列表:

(defn get-author-name-by-id [target-id]
  (if-let [author (some #(when (check-by-id % target-id) %) authors)]
    (:name author)
    nil))

调用示例:

(get-author-name-by-id 300) ; => "Jeff Dean"
(get-author-name-by-id 999) ; => nil

内容的提问来源于stack exchange,提问作者QuintessentialGamer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 06:20:58