This is a read-only archive of lispforum.com. The forum was locked to new users and posts and is preserved here as static HTML from a database snapshot taken on 2019-09-07.

Quicksort?

3 posts · 2901 views

Hello,

Could anyone help me with kinda my kinda clueless fumbling? ^_^; (I'm kinda new to the whole programming thing.)

I was thinking that it'd be kinda neat to be able to take the data from my school work and run correlation tests on everything against everything. I'm trying to implement quicksort as the first step in doing that.

Anyway, first I tried writing it out like this:
(defun test (lst)
  (let ((pivot (car lst))
	(smaller-than (remove-if (< pivot) lst) )
	(larger-than (remove-if (> pivot) lst) ))
    (setf pivot (cons (test smaller-than) pivot))
    (cons pivot (test larger-than))))
However SBCL is complained that pivot isn't defined yet:
 warning: 
    undefined variable: PIVOT
    --> PROGN 
    ==>
      (THE REAL PIVOT)
Which was kinda confusing me because I told it what pivot was as the first thing.

I did think maybe you weren't allowed have one definition in let dependent on something else in the let. Which seems supported by a quick test in the REPL:
(let (
	       (x 1)
	       (y (+ x 1))))
; in: LET ((X 1) (Y (+ X 1)))
;     (LET ((X 1) (Y (+ X 1)))
;       )
; 
; caught STYLE-WARNING:
;   The variable X is defined but never used.
; 
; caught STYLE-WARNING:
;   The variable Y is defined but never used.

; in: LET ((X 1) (Y (+ X 1)))
;     (+ X 1)
; 
; caught WARNING:
;   undefined variable: X
Anyway, then I tried this:
(defun test (lst)
  (defvar pivot (car lst))
  (defvar smaller-than (remove-if (< pivot) lst) )
  (defvar larger-than (remove-if (> pivot) lst) )

    (setf pivot (cons (test smaller-than) pivot))
    (cons pivot (test larger-than))))
Which among other things said -
  warning: 
    undefined variable: PIVOT
    --> PROGN 
    ==>
      (THE REAL PIVOT)
    
  warning: undefined variable: SMALLER-THAN
I suppose it makes sense that smaller-than wouldn't be defined if pivot wasn't. But then why's larger-than not throwing its own warning?

Did think I might not understand how defvar was used but this works:
(defvar x (car '(1 2)))

=> X

X

=> 1
So, yeah, I'm just kinda really confused now.

SBCL if that's relevant.

Thanks! Apologies if this is in the wrong place ^_^

Re: Quicksort?

The bindings in a let block are not guaranteed to be handled in sequence. They might be evaluated in a different order than specified, or evaluated in parallel on a multi-threaded implementation.

If you wish to have the bindings evaluated in a specific order (so later bindings can reference earlier ones) then you should use let*.
  (let* ((x 10)
   (y 20)
   (z (+ x y)) )
    (print z) )

Re: Quicksort?

Ah, excellent. Thank you! :D