Clojure: Remove value in all leaves of a tree

Viewed 162

I implemented a trie in clojure but I'm struggling with a remove-values function. The structure I use looks like this:

(def trie {\a {:value #{"val1" "val2"}}
           \b {\c     {:value #{"val1"}}
               :value #{"val2"}}})

I want to call a function like this (remove-value trie "val1") and get a structure where all instances of "val1" are removed from the sets in the leave nodes. The resulting trie would look like this:

{\a {:value #{"val2"}}
 \b {\c     {:value #{}}
     :value #{"val2"}}}

Or better yet:

{\a {:value #{"val2"}}
 \b {:value #{"val2"}}}

From what I've seen here on SO this could probably be done in five lines of clojure but I can't figure out how. Also I'm not married to the data structure, if you need to alter it for an idiomatic version to work, feel free, as long as it's still a trie.

4 Answers

One way would be using postwalk. e.g.

(def trie {\a {:value #{"val1" "val2"}}
           \b {\c     {:value #{"val1"}}
               :value #{"val2"}}})
; #'user/trie
(require '[clojure.walk :refer [postwalk]])
; nil
(doc postwalk)
; -------------------------
; clojure.walk/postwalk
; ([f form])
;   Performs a depth-first, post-order traversal of form.  Calls f on
;   each sub-form, uses f's return value in place of the original.
;   Recognizes all Clojure data structures. Consumes seqs as with doall.
; nil
(postwalk #(if (set? %) (disj % "val1") %) trie)
; {\a {:value #{"val2"}}, \b {\c {:value #{}}, :value #{"val2"}}}

From there you can also do the filter on maps (dissoc char keys, if they no longer hold any value)

I would suggest to use very regular structure of trie: A map whose first entry is always :value with a #{} of value. All other keys are children which contain as values themselvers tries. (Meaning they have a :value key at the beginning!)

Then define car/first, cdr/rest, cons, map for hash-maps (-map).

(defn first-map [m]
  (let [k (first (keys m))]
     {k (k m)}))

(defn rest-map [m]
  (into {} (map (fn [k] {k (k m)}) (rest (keys m)))))

(defn cons-map [m1 m2]
  (into {} (concat m1 m2)))

(defn map-map [f m & args]
  (into {} (map (fn [k] {k (apply f (k m) args)}) 
                (keys m))))

Try them out:

(def m {:a 1 :b 2 :c 3})

(first-map m)                 ;; => {:a 1}
(rest-map m)                  ;; => {:b 2 :c 3}
(cons-map {:a 1} {:b 2 :c 3}) ;; => {:a 1 :b 2 :c 3}
(map-map #(+ % 1) m)          ;; => {:a 2, :b 3, :c 4}
(map-map #(+ %1 %2) m 1)      ;; => {:a 2, :b 3, :c 4}

Then, using them define remove-value

(defn remove-value [trie val]
  (cons-map {:value (disj (:value (first-map trie)) val)}
            (map-map remove-value (rest-map trie) val)))

Originally, I wrote:

(defn remove-value [trie val]
  (cond (empty? (rest-map trie))
        {:value (disj (:value (first-map trie)) val)}
        :else (cons-map {:value (disj (:value (first-map trie)) val)}
                        (map-map remove-value (rest-map trie) val))))

But then realized that the :else branch alone does this automatically since map-map on an empty (rest-map trie) results in just {:value (disj (:value (first-map trie)) val)} - which can be alternatively expressed also as (let [[k v] (first-map trie)] {k (disj v val)}).

Your trie would be:

(def trie {:value #{}
           :a {:value #{"val1" "val2"}}
           :b {:value #{"val2"}
               :c {:value #{"val1"}}}})

Note: a tree in toplevel will always begin with :value #{} (the root of the tree). :value's value will be always a set either empty #{} or with one or multiple elements in it. So, every child is a complete trie in itself.

user=> (remove-value trie "val1")
{:value #{}, :a {:value #{"val2"}}, :b {:value #{"val2"}, :c {:value #{}}}}
user=> (remove-value trie "val2")
{:value #{}, :a {:value #{"val1"}}, :b {:value #{}, :c {:value #{"val1"}}}}
(require '[com.rpl.specter :as s])

(let [trie {\a {:value #{"val1" "val2"}}
                \b {\c     {:value #{"val1"}}
                    :value #{"val2"}}}]
        (->> trie
             (s/setval (s/compact (s/walker set?) (s/set-elem "val1")) s/NONE)
             (s/setval (s/compact (s/walker #(and (map? %) (empty? %)))) s/NONE)))

This one was trickier than I thought! I made at least 2 mistakes when I was trying to answer quickly. Here is a working version from a template project:

(ns tst.demo.core
  (:use demo.core  tupelo.test)
  (:require
    [clojure.walk :as walk]
    [tupelo.core :as t]
    ))

(defn remove-value
  [data remove-val]
  (walk/postwalk
    (fn [item]
      (if (instance? clojure.lang.MapEntry item)
        (let [[k v] item] ; destructure MapEntry into key/val pair
          ; must return a MapEntry (or a 2-vector equivalent)
          [k (if (= k :value)
               (disj v remove-val)
               v)]) ; must return item if unchanged
        item)) ; must return item if unchanged
    data))

(dotest
  (let [my-data {\a {:value #{"val1" "val2"}}
                 \b {\c     {:value #{"val1"}}
                     :value #{"val2"}}}
        ]
    (is= (remove-value my-data "val1")
      {\a {:value #{"val2"}}
       \b {\c     {:value #{}}
           :value #{"val2"}}})))

You can simplify it a bit if you use cond-it->

(defn remove-value
  [data remove-val]
  (walk/postwalk
    (fn [item]
      (t/cond-it-> item
        (instance? clojure.lang.MapEntry it)
        (let [[k v] it] ; destructure MapEntry into key/val pair
          (t/map-entry ; must return a MapEntry (or a 2-vector equivalent)
            k (t/cond-it-> v
                (= k :value) (disj it remove-val))))))
    data))

You may also be interested in better-cond.


For more complicated tree structure manipulation, you may be interested in Tupelo Forest.

Related