lisp - Why does replacing "(null x)" with "(null (cdr x))" make this code work? -


i'm newbie in lisp. i'm trying write bubble sort function in lisp.

this i've done far.

(defun mysort (x)   (if (null  x) x     (if (< (car x) (cadr x))      (cons (car x) (mysort (cdr l)))      (cons (cadr x) (mysort (cons (car x) (cddr x))))))) 

i'm getting error

nil not real number 

when modified code (after referring several codes)-

(defun mysort (x)   (if (null  (cdr x)) x    (if (< (car x) (cadr x))     (cons (car x) (mysort (cdr l)))     (cons (cadr x) (mysort (cons (car x) (cddr x))))))) 

now works fine.

why replacing (if (null x) x...) (if (null (cdr x)) x...) make difference?

also, i'm calling mysort function run (length x) number of times. possible achieve complete sorting in single recursive loop, using basic functions?

to comparison need @ least 2 elements checking if x nil not enough.

checking if (cdr x) nil nice way check list length @ least 2 because nil special , if it's not cons cell it's guaranteed (cdr nil) nil.

the error getting because nil not number cannot compare < number , happening when executing (< (car x) (cadr x)) when x list single element.

about sorting in single recursive call use definition of sorting:

  • an empty list sorted
  • a non-empty list sorted if first element minimum of list , rest of list sorted.

this leads to

(defun mysort (x)   (if x       (let ((minimum (reduce #'min x)))         (cons minimum               (mysort (remove minimum x :count 1)))))) 

that, way, very inefficient way sorting.


Comments

Popular posts from this blog

Why can rails not find a route created by a helper? -

javascript - jquery or ashx not working -

opencv - DataType<cv::detail::deriv_type>::depth what is it used for -