ren
ren

Reputation: 270

APL / APLX: value error when using an if statement inside a for loop

I'm attempting to implement quicksort in APLX, but I can't seem to fix this value error I keep getting from the statement :If((ITEM COMPARE PIVOT)≤0). After some testing, I believe the problem lies with the fact that I am using an If statement inside a For loop, but I don't know why that would be a problem. Here's the entire function (or rather operator), just in case the problem lies elsewhere:

(note than COMPARE is a comparator function that I pass to quicksort)

(COMPARE QSORT)ARRAY
⍝ If the array has a size of 1
⍝ or less, return
:If (⍴ARRAY) ≤ 1
  ARRAY
:endif
⍝ set pivot to last element in array
PIVOTINDEX ← ⍴ARRAY
PIVOT ← PIVOTINDEX⌷ARRAY
⍝ remove pivot from array by assigning
⍝ array to all elements up to pivot index
ARRAY ← (PIVOTINDEX-1)↑ARRAY
⍝ Make empty vectors for values greater
⍝ than and less than the pivot
LESSER ← ⍳0
GREATER ← ⍳0
⍝ loop over ARRAY, place items in GREATER
⍝ or LESSER where appropriate
:For ITEM :In ARRAY
  :If((ITEM COMPARE PIVOT)≤0)
    LESSER ← LESSER,ITEM
  :Else
    GREATER ← GREATER,ITEM
  :EndIf
:EndFor
SORTED ← SORTED,(COMPARE QSORT LESSER)
SORTED ← SORTED,PIVOT
SORTED ← SORTED,(COMPARE QSORT GREATER)
SORTED

Upvotes: 1

Views: 153

Answers (1)

MBaas
MBaas

Reputation: 7530

Hmm, I'm afraid I'm not familiar with APLX, but here are my 0.02$ regardless:

  1. You know about ⍋? So I assume this is an educational excercise... ;-)
  2. There is no problem with the control-structures, but your COMPARE -fn does not return a result, so when you then try to use the result (by referring to COMPARE), that creates the error. The function header should probably be ∇ RESULT←(COMPARE QSORT)ARRAY (session-output is not considered "function-result" - this needs explicit assignment!)
  3. Also note that localizing name of variables is considered good practice.

Upvotes: 2

Related Questions