diff --git a/README.md b/README.md index 2bacc0a..cd75eca 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,7 @@ Or you can just dump `dash.el` in your load path somewhere. * [-interpose](#-interpose-sep-list) `(sep list)` * [-interleave](#-interleave-rest-lists) `(&rest lists)` * [-first](#-first-pred-list) `(pred list)` +* [-union](#-union-list-list) `(list list2)` * [-difference](#-difference-list-list) `(list list2)` * [-intersection](#-intersection-list-list) `(list list2)` * [-distinct](#-distinct-list) `(list)` @@ -395,6 +396,18 @@ To get the first item in the list no questions asked, use `car`. (--first (> it 2) '(1 2 3)) ;; => 3 ``` +### -union `(list list2)` + +Return a new list containing the elements of `list1` and elements of `list2` that are not in `list1`. +The test for equality is done with `equal`, +or with `-compare-fn` if that's non-nil. + +```cl +(-union '(1 2 3) '(3 4 5)) ;; => '(1 2 3 4 5) +(-union '(1 2 3 4) '()) ;; => '(1 2 3 4) +(-union '(1 1 2 2) '(3 2 1)) ;; => '(1 1 2 2 3) +``` + ### -difference `(list list2)` Return a new list with only the members of `list` that are not in `list2`. diff --git a/dash.el b/dash.el index e76a81e..7933f53 100644 --- a/dash.el +++ b/dash.el @@ -472,7 +472,16 @@ or with `-compare-fn' if that's non-nil. Alias: `-uniq'" (let (result) - (--each list (when (not (-contains? result it)) (!cons it result))) + (--each list (unless (-contains? result it) (!cons it result))) + (nreverse result))) + +(defun -union (list list2) + "Return a new list containing the elements of LIST1 and elements of LIST2 that are not in LIST1. +The test for equality is done with `equal', +or with `-compare-fn' if that's non-nil." + (let (result) + (--each list (!cons it result)) + (--each list2 (unless (-contains? result it) (!cons it result))) (nreverse result))) (defalias '-uniq '-distinct) diff --git a/examples.el b/examples.el index 2d1fe27..bb07fa0 100644 --- a/examples.el +++ b/examples.el @@ -161,6 +161,11 @@ (-first 'even? '(1 3 5)) => nil (--first (> it 2) '(1 2 3)) => 3) +(defexamples -union + (-union '(1 2 3) '(3 4 5)) => '(1 2 3 4 5) + (-union '(1 2 3 4) '()) => '(1 2 3 4) + (-union '(1 1 2 2) '(3 2 1)) => '(1 1 2 2 3)) + (defexamples -difference (-difference '() '()) => '() (-difference '(1 2 3) '(4 5 6)) => '(1 2 3)