Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pulling values from complex lists in Clojure

Tags:

clojure

I'm trying to pull the values out of a complicated list structure.

Given something like this:

[{:a "whatever" :b [:c "foo"]} :e {:f "boo"} :g {:h [:i 62281]}]

I'd like to get:

["whatever" "foo" "boo" 62281]

So far I've only gotten to this point:

((62281) nil (boo) nil whatever foo)

Here's the code:

(defn get-values [params]
  (apply conj
         (map (fn [part]
                (if (not (keyword? part))
                    (map (fn [v]
                           (if (vector? v)
                               (last v)
                               v))
                         (vals part))))
              params)))
  1. I can't seem to get rid of the nil's
  2. I can't figure out why the values after a certain point are in lists.
  3. I figure there's got to be a better way to do this.
like image 851
Mike Flynn Avatar asked Sep 02 '26 10:09

Mike Flynn


1 Answers

Fix the data structure and everything will fall in place. As of now your data structure isn't consistent at all and that will make any function that touch this data way more complicated and error prone. You can model this data as a map:

(def data  {:a "whatever"
            :b nil
            :c "foo"
            :e nil
            :f "boo"
            :g nil
            :h nil
            :i 62281})

And then to get the desired result:

(->> (vals data)
     (filter (comp not nil?))
     (into []))

But for some strange reason you still want to parse the data structure you provided then:

(defn get-values [data]
  (->> (map #(if (map? %) (into [] %) %)  data)
       flatten
       (filter #(or (string? %) (number? %)))
       (into [])))
like image 155
Ankur Avatar answered Sep 05 '26 16:09

Ankur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!