什么是惯用的 Clojure 来“删除"?列表中多个实例中的单个实例? [英] What is idiomatic Clojure to "remove" a single instance from many in a list?

查看:18
本文介绍了什么是惯用的 Clojure 来“删除"?列表中多个实例中的单个实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个列表,其中可能包含比较相等的元素.我想要一个类似的列表,但删除了一个元素.因此,从 (:a :b :c :b :d) 我希望能够删除"仅 one :b 以获取 (:a :c :b :d).

上下文是纸牌游戏中的一手牌,其中使用两副标准纸牌,因此可能有重复的纸牌,但仍一次打出一张.

我有工作代码,见下文.在 Clojure 中是否有更多惯用的方法来做到这一点?

(defn remove-one [c left right](如果(= 右())剩下(如果(= c(右一))(concat (左后) (rest right))(remove-one c (cons (first right) left) (rest right)))))(defn remove-card [c 卡](删除一张c()卡))

这是我不久前得到的 Scala 答案:什么是 Scala 惯用的删除"方式?不可变列表中的一个元素?

解决方案

怎么样:

(let [[n m] (split-with (partial not= :b) [:a :b :c :b :d])] (concat n (rest m)))

在 :b 处拆分列表,然后删除 :b 并连接两个列表.

I have a list, which may contain elements that will compare as equal. I would like a similar list, but with one element removed. So from (:a :b :c :b :d) I would like to be able to "remove" just one :b to get (:a :c :b :d).

The context is a hand in a card game where two decks of standard cards are in play, so there may be duplicate cards but still played one at a time.

I have working code, see below. Are there more idiomatic ways to do this in Clojure?

(defn remove-one [c left right]
  (if (= right ())
    left
    (if (= c (first right))
      (concat (reverse left) (rest right))
      (remove-one c (cons (first right) left) (rest right)))))

(defn remove-card [c cards]
  (remove-one c () cards))

Here are the Scala answers I got a while ago: What is an idiomatic Scala way to "remove" one element from an immutable List?

解决方案

How about:

(let [[n m] (split-with (partial not= :b) [:a :b :c :b :d])] (concat n (rest m)))

Which splits the list at :b and then removes the :b and concats the two lists.

这篇关于什么是惯用的 Clojure 来“删除"?列表中多个实例中的单个实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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