I have this following proc maxIndex that returns the index that holds the largest item in my heap structure:

proc maxIndex[Comparable](heap: Heap[Comparable]; currenti, lefti, righti: int): int {.inline.} =
  # C > L and C > R ? C
  # L > C and L > R ? L
  # R > C and R > L ? R
  if heap.data[currenti] >= heap.data[lefti] and heap.data[currenti] >= heap.data[lefti]:
    return currenti
  if heap.data[lefti] >= heap.data[currenti] and heap.data[lefti] >= heap.data[righti]:
    return lefti
  if heap.data[righti] >= heap.data[currenti] and heap.data[righti] >= heap.data[lefti]:
    return righti
  quit("Logical error reached.")  # TODO: cleanup

Now I have to implement a minIndex proc. There is obviously a lot of code duplication because the only difference between these to procs is the comparison operation.

I would like to know if it's possible to pass a > or < operator to a template so I don't have to re-implement the whole body.

Like this:

proc fn1(a, b: int; fn: proc(x, y: int): bool) =
    echo(fn(a, b))

fn1(2, 10, `>`)  # should print false
fn1(20, 10, `>`)  # should print true

2018-02-12 10:45:05

Should be just fine.

Also, you code can potentially benefit from a shortcut inside a proc:

template d: auto = heap.data

2018-02-12 11:27:01