Skip to content

Instantly share code, notes, and snippets.

@piotr-yuxuan
Created July 23, 2015 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save piotr-yuxuan/4d9094b0ffbf9885d4ab to your computer and use it in GitHub Desktop.
Save piotr-yuxuan/4d9094b0ffbf9885d4ab to your computer and use it in GitHub Desktop.
Buggy Clojure assoc-in implementation
(defn my-assoc-in
"Implement built-in assoc-in in the way I get it. It nicely inserts a value in the nested map and doesn't overwrite."
[map keys value]
(let [[k & keys] (reverse keys)]
(loop [[key & keys] keys
final map
initial (assoc {} k value)]
(if (not (empty? keys))
(recur keys
final
(assoc (get-in final (reverse keys)) key initial))
(assoc final key initial)))))
;; It seems to behave properly…
(my-assoc-in {:a 1 :b 2 :c {:d 3 :e 4 :f 5}} [:c :d :e] :value)
;=> {:c {:e 4, :d {:e :value}, :f 5}, :b 2, :a 1}
;; …but there is a flaw ><
(my-assoc-in-old {:a 1 :b 2 :c {:d 3 :e 4 :f 5}} [:c :d] :value)
;=> {:c {:d :value}, :b 2, :a 1}
@piotr-yuxuan
Copy link
Author

Hi guys!

I'm new-comer in both Clojure and functional programming worlds. I've been spending some time on implementing assoc-in in a personal fashion. Unfortunately, what I've got seems to work properly in first examples… but it doesn't work properly yet for all cases.

I'd be thankful if some of you would explain me where I'm wrong and how I can get it right :-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment