-1

I get an error message for the code below. It's just a simple syntax error, but as a beginner I'm not sure what's wrong. Anybody know?

(define qsort
  (lambda (input-list)

    (define sort-pivot-iter
      (lambda (input-list pivot acc)
        (let ([current             (first input-list)]
          [pivot-less          (first acc)]
          [pivot-greater-equal (first (rest acc))])
            (cond (
                 [(empty? input-list) acc]
                 [(<  current pivot) (sort-pivot-iter (rest input-list) pivot  
                  '((cons current pivot-less) pivot-greater-equal))]
                 [(>= current pivot) (sort-pivot-iter (rest input-list) pivot  
                  '(pivot-less (cons current pivot-greater-equal)))])))))

    (let* ([pivot (first input-list)]
       [pivot-sorted (sort-pivot-iter 
                   (rest input-list) pivot (list empty empty))]
       [left (first pivot-sorted)]
       [right (first (rest pivot-sorted))])
        (cond
          [(< (length input-list) 2) input-list]
          [else (append (qsort left) '(pivot) (qsort right))]))))


(qsort '(2 3 1))
Brian Yeh
  • 3,119
  • 3
  • 26
  • 40

1 Answers1

2

You have an extra set of parentheses around the clauses of the cond form, which is causing the entire body to be parsed as a single clause.

This means [(empty? input-list) acc] is being treated as an expression (the clause’s condition), which is equivalent to ((empty? input-list) acc), since square brackets and parentheses are interchangeable. This attempts to invoke the result of empty? as a procedure, which causes the error.

A slightly simplified grammar for cond is as follows:

(cond cond-clause ...)

  cond-clause = [test-expr body ...]
              | [else body ...+]

Notice that each cond-clause is wrapped in brackets (or parens), but the clauses themselves are not wrapped in any way. Therefore, your cond form should look like this:

(cond
  [(empty? input-list) acc]
  [(<  current pivot) (sort-pivot-iter (rest input-list) pivot  
                                       '((cons current pivot-less) pivot-greater-equal))]
  [(>= current pivot) (sort-pivot-iter (rest input-list) pivot  
                                       '(pivot-less (cons current pivot-greater-equal)))])

Your code still has some other problems, but those are unrelated to the error message in your question. For one thing, your use of quote (aka ') here does not make sense to me, so you may also want to read What is the difference between quote and list? to help with that.

Community
  • 1
  • 1
Alexis King
  • 43,109
  • 15
  • 131
  • 205