What is idiomatic Clojure to “remove” a single instance from many in a list?

前端 未结 3 1177
悲&欢浪女
悲&欢浪女 2020-12-18 20:10

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

3条回答
  •  既然无缘
    2020-12-18 20:38

    It is surprising there is not a high-level API to do something like this. Here is another version similar to @amalloy and @James that uses recur in order not to stack overflow.

    (defn remove-once [x c]                                                                                                                                                                                                                     
      (letfn [(rmv [x c1 c2 b]                                                                                                                                                                                                                  
                (if-let [[v & c] (seq c1)]                                                                                                                                                                                                      
                  (if  (and (= x v) b)                                                                                                                                                                                                          
                    (recur x c c2 false)                                                                                                                                                                                                        
                    (recur x c (cons v c2) b))                                                                                                                                                                                                  
                  c2))]                                                                                                                                                                                                                         
        (lazy-seq (reverse (rmv x c '() true)))))                                                                                                                                                                                               
    
    (remove-once :b [:a :b :c :b :d])
    ;; (:a :c :b :d)
    

提交回复
热议问题