Hi, - Thanks in advance for any help.
I am new to lisp, and have been spending all day debugging this small number
sorting program with only minor success. I would use the sort function, but
this is an assignment for school, so I am writing a simple bubblesort type
thing - just to sort numbers.
The sorting actually works, but it crashes after it is done and does not
return anything. I hope to an experienced lisp programmer that my error
will be obvious.
Here is the code. First is a simple swap function. Then the sortme
function.
(defun swap (L p1 p2)
(rotatef (elt L p1) (elt L p2))
L)
(defun sortem (L) ;define the
function
((setq i 0) ;set
the big iterator to 0
(while (< i (- (length L) 2)) ;while number
of times through whole list
(setq ii 0) ;set
the small iterator to 0
(while (< ii (- (length L) 1)) ;while
number of items in list
(if (> (nth ii L) (nth (+ ii 1) L)) ;if item 1
is bigger than item 2,
(swap L ii (+ ii 1)) ;swap
them
)
;else do nothing
(setq ii (+ ii 1)))
;increment small counter
(setq i (+ i 1))))
;increment big counter
L
;return the list
)
It seems to have a problem with the line (setq i 0) as I have to reset this
each time I run it, or else the sort will not happen. If I do a (setq i 0)
and (setq ii 0) before I run the (sortem a) command, it sorts, but returns
with an error. But even if I pull out those lines it still crashes.
Here is the eror I get after setting i and ii before running the function.
It sorted the list fine and here is what it said:
[1] CG-USER(166): a
(2 8 3 9 4 7 5 6)
[1] CG-USER(167): i
7
[1] CG-USER(168): ii
7
[1] CG-USER(169): (setq i 0)
0
[1] CG-USER(170): (setq ii 0)
0
[1] CG-USER(171): (sortem a)
1[1]: (SORTEM (2 8 3 9 4 7 5 6))
Error: Illegal function object: (SETQ I 0).
[condition type: PROGRAM-ERROR]
1[1]: returned-by-throwing :POP 0
[1] CG-USER(172): a
(2 3 4 5 6 7 8 9)
Any ideas?
Thanks for your help!
Shane