Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I keep getting empty maps when i am passing data into two hash maps in clojure, i know that the data is being sent through the functions as i have used print statements that show it correct data, its just when i assoc the data to the map it doesnt appear to do anything and leaves me with {}

Can anyone see what i am doing wrong??

(defn sort-string [y]
  (apply str (sort y)))

(defn get-unique [y]
  (let [x (sort-string (str/lower-case y))
        hashmap1 (hash-map)
        hashmap2 (hash-map)]

    (if-not (contains? hashmap1 x)
      (assoc hashmap1 x, y)
      (assoc hashmap2 y, y))

    (if-not (get hashmap1 x) y)
    (dissoc hashmap2 (get hashmap1 x))))

(for [strings '("door" " rood" "pen" "open" "high" "low" "wall" "lawl" "#")]
  (get-unique strings))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
249 views
Welcome To Ask or Share your Answers For Others

1 Answer

Clojure maps are immutable. So the assocs, which return modified maps, have no effect, as the returned values are not used.

I don't know what you're trying to do, but the following might get you on the right lines:

(defn get-unique [y]
  (let [x (sort-string (str/lower-case y))
        hashmap1 (hash-map)
        hashmap2 (hash-map)
        [hashmap1 hashmap2]  (if-not (contains? hashmap1 x)
                               [(assoc hashmap1 x, y) (assoc hashmap2 y, y)]
                               [hashmap1 hashmap2])]

    (if-not (= (get hashmap1 x) y)
      (dissoc hashmap2 (get hashmap1 x))
      hashmap2)))

For example,

(for [strings '("door" " rood" "pen" "open" "high" "low" "wall" "lawl" "#")]
  (get-unique strings))

;({"door" "door"} {" rood" " rood"} {"pen" "pen"} {"open" "open"} {"high" "high"} {"low" "low"} {"wall" "wall"} {"lawl" "lawl"} {"#" "#"})

Now that your comment tells me you are trying to group anagrams together, using sort-string to test for equivalences ...

You can do this using group-by. For example,

(let [strings '("door" " rood" "pen" "open" "high" "low" "wall" "lawl" "#")]
  (group-by sort-string strings))

... produces ...

{"door" ["door" "rood"], "enp" ["pen"], "enop" ["open"], "ghhi" ["high"], "low" ["low"], "allw" ["wall" "lawl"], "#" ["#"]}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...