I'm currently trying to implement this java quicksort implementation in nim, but it uses both postfix and prefix increment and decrement operators inside of the heads of multiple while loops:
while (less(a[++i], v))
if (i == hi) break;
while (less(v, a[--j]))
if (j == lo) break;
Is there any way I can implement something like this in nim (inside a while loop head), and if possible elegantly?proc `++`*[T: TOrdinal|uint|uint64](x: var T): T =
x += 1
x
proc `--`*[T: TOrdinal|uint|uint64](x: var T): T =
x -= 1
x
# instead of postfix versions
proc `+++`*[T: TOrdinal|uint|uint64](x: var T): T =
result = x
x += 1
proc `---`*[T: TOrdinal|uint|uint64](x: var T): T =
result = x
x -= 1
You can rewrite it with templates, then last 2 can be like:
template `+++`*[T: TOrdinal|uint|uint64](x: var T): T =
let result = x
x += 1
result
It may be preferred style not to use ++ and the like. Quicksort looks pretty clean without them:
proc quickSort[T](a: var openarray[T], l, r: int) =
if r <= l: return
let pivot = a[l]
var (i, j) = (l, r)
while i <= j:
if a[i] < pivot:
inc i
elif a[j] > pivot:
dec j
elif i <= j:
swap a[i], a[j]
inc i
dec j
quickSort(a, l, j)
quickSort(a, i, r)
proc quickSort*[T](a: var openarray[T]) =
quickSort(a, 0, a.high)
var a = @[4, 65, 2, -31, 0, 99, 2, 83, 782]
quickSort a
echo a