how convert this:
[a b c d e]
or this:
(e d c b a) ;(rseq [a b c d e])
to this:
[a[b[c[d[e]]]]]
i've been wracking brain , feel there simple solution! :-\
ultimately want this:
[a b c d e] [a b c x y] [a b c d j k]
as this:
{a {b {c {d {e} {j {k}} {x {y}}}}
which think conj with
(update: added answer new question added in edit below answer original question.)
i've answered question in #clojure recently.
here 2 approaches: f
pretty spec directly transformed code, creates seq -- (next xs)
-- gets poured new vector @ each step; g
better version allocates objects occur in output, plus vector , seq links traverse it:
;; [1 2 3] -> [1 [2 [3]]] ;; naive, quadratic: (defn f [xs] (if (next xs) [(first xs) (vec (f (next xs)))] (vec xs))) ;; allocates output + 1 vector + linear number of seq links, ;; linear overall: (defn g [v] (reduce (fn [acc x] [x acc]) [(peek v)] (rseq (pop v))))
nb. i'm overlooking usual logarithmic factors arising vector operations (so soft-o complexity).
as producing nested map, above isn't particularly useful. here's 1 approach:
(defn h ([v] (h nil v)) ([m v] (assoc-in m v nil))) (h [1 2 3 4]) ;= {1 {2 {3 {4 nil}}}} (def data '[[a b c d e] [a b c x y] [a b c d j k]]) (reduce h {} data) ;= {a {b {c {x {y nil}, d {j {k nil}, e nil}}}}}
i'm using nil
"terminator", since {y}
(as found in answer text) not well-formed literal. true
might more convenient choice if plan call these maps functions check presence of keys.
Comments
Post a Comment