Associative array/Merging: Difference between revisions

Add Common Lisp implementation
(Added 11l)
(Add Common Lisp implementation)
Line 459:
<pre>{"name" => "Rocket Skates", "price" => 15.25, "color" => "red", "year" => 1974}
</pre>
 
=={{header|Common Lisp}}==
In Common Lisp, the value of a key in an alist or a plist is defined as the first value in the list with a matching key or indicator. Thus, all that is necessary to implement this algorithm for either is the following:
<lang lisp>
(append list2 list1)
</lang>
 
These implementations for alists and plists are more complicated, but avoid duplicate keys in the results:
<lang lisp>
(defun merge-alists (alist1 alist2)
(nconc
(loop :for pair1 :in alist1
:for pair2 := (assoc (car pair1) alist2)
:do (setf alist2 (remove pair2 alist2))
:collect (or pair2 pair1))
alist2))
 
(defun merge-plists (plist1 plist2)
(let ((res '()))
(loop :for (key val) :on plist1 :by #'cddr
:do (setf (getf res key) val))
(loop :for (key val) :on plist2 :by #'cddr
:do (setf (getf res key) val))
res))
</lang>
 
=={{header|Dart}}==
Anonymous user