Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add -insert-sorted #244

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
19 changes: 19 additions & 0 deletions dash.el
Expand Up @@ -881,6 +881,23 @@ See also: `-splice', `-splice-list'"
(let ((split-list (-split-at n list)))
(nconc (car split-list) (cons x (cadr split-list)))))

(defun -insert-sorted (comparator item list)
"Using COMPARATOR insert ITEM into sorted LIST.

It is assumed that LIST is already sorted on input.

The new item is inserted at the first position where

(funcall comparator x item)

returns nil. X is the \"current\" item from the input list."
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add a note about -not being able to flip predicates.

(let ((place (-split-with (lambda (x) (funcall comparator x item)) list)))
(-concat (car place) (list item) (cadr place))))

(defmacro --insert-sorted (form item list)
"Anaphoric form of `-insert-sorted'."
`(-insert-sorted (lambda (it other) ,form) ,list))

(defun -replace-at (n x list)
"Return a list with element at Nth position in LIST replaced with X.

Expand Down Expand Up @@ -2640,6 +2657,8 @@ structure such as plist or alist."
"-split-at"
"-rotate"
"-insert-at"
"-insert-sorted"
"--insert-sorted"
"-replace-at"
"-update-at"
"--update-at"
Expand Down
7 changes: 7 additions & 0 deletions dev/examples.el
Expand Up @@ -256,6 +256,13 @@ new list."
(-insert-at 1 'x '(a b c)) => '(a x b c)
(-insert-at 12 'x '(a b c)) => '(a b c x))

(defexamples -insert-sorted
(-insert-sorted '< 4 '(1 2 3 5 6 7)) => '(1 2 3 4 5 6 7)
(-insert-sorted (lambda (a b) (< (car a) (car b))) '(3 . "new") '((1) (2) (3 . "old"))) => '((1) (2) (3 . "new") (3 . "old"))
(-insert-sorted '< 1 '(2 3 5 6 7)) => '(1 2 3 5 6 7)
(-insert-sorted '< 8 '(2 3 5 6 7)) => '(2 3 5 6 7 8)
(-insert-sorted '< 1 nil) => '(1))

(defexamples -replace-at
(-replace-at 0 9 '(0 1 2 3 4 5)) => '(9 1 2 3 4 5)
(-replace-at 1 9 '(0 1 2 3 4 5)) => '(0 9 2 3 4 5)
Expand Down