'trying to convert C to Lisp
I am trying to convert this code to lisp code. But don't know how to do it is it right?
for (j=i-1; j>=0 && list[j]>key; j--) {
list[j+1] = list[j];
}
(loop (set j (- i 1))
(setq (aref x(+ j 1) (aref x j))
(setq j (- j 1)
(when (or(>= j 0)
(> (aref x j) key)
(return-from foo 0))
Solution 1:[1]
The most straightforward way is to use the extended loop
:
(loop :for j :downfrom (1- i)
:while (and (not (minusp j))
(> (aref list j) key))
:do (setf (aref list (1+ j))
(aref list j)))
(Note: I prefer to use keywords for loop keywords, because that gives me nice syntax highlighting for free. You will often also find them as plain symbols, e. g. for
instead of :for
.)
Solution 2:[2]
though it's not a word-by-word translation, i would probably go with something like this:
(let* ((data (vector 1 2 3 4 5 6 7 8 9))
(key 3)
(pos (or (position-if (lambda (x) (<= x key)) data :from-end t)
0)))
(setf (subseq data (1+ pos))
(subseq data pos))
data)
Looks more like a CL style to me.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Svante |
Solution 2 |