Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure Zipper of nested Maps repressing a TRIE

How can I create a Clojure zipper for a TRIE, represented by nested maps, were the keys are the letters.?

Something like this:

{\b {\a {\n {\a {\n {\a {'$ '$}}}}}} \a {\n {\a {'$ '$}}}}

Represents a trie with 2 words 'banana' and 'ana'. (If necessary , its possible to make some changes here in maps..)

I've tried to pass map? vals assoc as the 3 functions to the zipper,respectively. But it doesnt seem to work..

What 3 functions should I use?

And how the insert-into-trie would look like based on the zipper ?

like image 429
0xMG Avatar asked Feb 21 '13 22:02

0xMG


1 Answers

map? vals #(zipmap (keys %1) %2) would do but doesn't support insertion/removal of children (since children are only values, you don't know which key to remove/add).

The map-zipper below does support insertion/removal because nodes are [k v] pairs (except the root which is a map).

(defn map-zipper [m]
  (z/zipper 
    (fn [x] (or (map? x) (map? (nth x 1))))
    (fn [x] (seq (if (map? x) x (nth x 1))))
    (fn [x children] 
      (if (map? x) 
        (into {} children) 
        (assoc x 1 (into {} children))))
    m))
like image 198
cgrand Avatar answered Oct 05 '22 23:10

cgrand