Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
258 views
in Technique[技术] by (71.8m points)

hashmap - Empty Maps in Clojure

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

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

1 Reply

0 votes
by (71.8m points)

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"], "#" ["#"]}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...