如何从地图中删除多个键? [英] How to remove multiple keys from a map?

查看:23
本文介绍了如何从地图中删除多个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个从地图中删除键的函数:

I have a function that removes a key from a map:

(defn remove-key [key map]
  (into {}
        (remove (fn [[k v]] (#{key} k))
                map)))

(remove-key :foo {:foo 1 :bar 2 :baz 3})

如何使用多个键应用此功能?

How do i apply this function using multiple keys?

(remove-keys [:foo :bar] {:foo 1 :bar 2 :baz 3})

我有一个使用 loop...recur 的实现.在 Clojure 中是否有更惯用的方法?

I have an implementation using loop...recur. Is there a more idiomatic way of doing this in Clojure?

(defn remove-keys [keys map]
  (loop [keys keys
         map map]
    (if (empty? keys)
      map
      (recur (rest keys) (remove-key (first keys) map)))))

推荐答案

您的 remove-key 函数包含在标准库函数 dissoc 中.dissoc 将一次删除多个键,但它希望键直接在参数列表中而不是在列表中给出.因此,您可以使用 apply 将其展平".

Your remove-key function is covered by the standard library function dissoc. dissoc will remove more than one key at a time, but it wants the keys to be given directly in the argument list rather than in a list. So you can use apply to "flatten" it out.

(apply dissoc {:foo 1, :bar 2, :baz 3} [:foo :bar])
==> {:baz 3}

这篇关于如何从地图中删除多个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆