-
-
Save piotr-yuxuan/4d9094b0ffbf9885d4ab to your computer and use it in GitHub Desktop.
Buggy Clojure assoc-in implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 :-)