How does the sort function work?

Hi all,

I’ve tried to sort an integer array with the sort function.

Var modeOffsets, notesInKey : integer array

Initialization
modeOffsets = [0, 2, 4, 5, 7, 9, 11]
notesInKey = Sort(modeOffsets, true)
End

I expect the array notesInKey to be equal to the array modeOffsets, however, I get an error message:
“Semantic error: Line 26, Col 5: Types are not compatible”

The Sort function does not return a value — (GPScript ain’t C :slight_smile: )

Cheers !

So when I compare to Pascal;
Sort is not a function but a procedure?

Absolutely. GP Script was very much inspired by the Pascal/Algol world. I even thought about using the term procedure when the “function” didn’t return anything. I still could allow it

On the same subject, how do you prefer the use of global versus local variables?
I see myself resorting to both: why return a value from a function if you can also change the global variable (which you would be returning it to) inside the function, directly?

But you can write your own real function

Var modeOffsets, notesInKey : integer array

function csort(a : Integer Array) returns integer array
 var at : Integer Array
 
 at = a
 Sort(at, true)
 
 result = at
end

Initialization
modeOffsets = [0, 2, 4, 5, 7, 9, 11]
notesInKey = csort(modeOffsets)
End

Functions should generally not modify global variables unless there’s no choice. Unfortunately, GPScript does not yet have scoping rules as local as I would like.

Or you could leave out that local variable and just write

function csort(a : Integer Array) returns integer array
   result = a
   Sort(result, true)
end

and save a copy assignmnet

1 Like