Search code examples
functional-programmingclojure

clojurescript thread macro nested vector problem


this is my function

(defn foo
      []
      (->> (conj (:countries list1)                         ;; ["UK" "USA" "IND"]
                 (:countries list2)                         ;; ["AUS" "NZ"]
                 (:countries list3)                         ;; "FRA"
                 )
           (some-other-operations)))

comment shows the data they fetches and I'm expecting my result to be like this

["UK" "USA" "IND" "AUS" "NZ" "FRA"]

but i don't why it gives me output like this

["UK" "USA" ["AUS" "NZ"] "FRA"]

it works fine though if i remove list2. then it produces output like this

["UK" "USA" "FRA"]

anyone any idea how can i fix this?


Solution

  • the root problem, as i see it, is an irregular :countries value type, being collection or atom in different cases. What i would propose, is ensure the :contries is always a collection and use concat. In case you don't have control over the data type (which often happens), i'd propose utility concatenation function, something like that:

    (defn concat* [& xs]
      (reduce (fn [acc x]
                ((if (sequential? x) into conj) acc x))
              [] xs))
    
    user> (concat* ["UK" "USA" "IND"] ["AUS" "NZ"] "FRA")
    ;;=> ["UK" "USA" "IND" "AUS" "NZ" "FRA"]
    

    as for me, i would discourage using flatten in production code, since it may lead to the whole bunch of errors when data type changes.