Hi guys
I am looking for a way to write code in nim that behaves similar to this Python piece
In [1]: import operator
In [2]: d = {'*': operator.mul, '+': operator.add}
In [3]: op = '+'
In [4]: d[op](2, 3)
Out[4]: 5
The problem is that I do not understand how I can store reference to an operator in a TableNim does not have "operator" module but you can quickly create your own little closure functions that use the operator. Looks nearly identical to python then:
import tables
let d = {
  '*': proc(a, b: int): int = a * b,
  '+': proc(a, b: int): int = a + b
}.toTable()
let op = '+'
echo d[op](2, 3)
The problem isn't that it's overloaded. + is a "magic" proc, it generates different inline code per backend, so it's not a real function. Overloads, including generic overloads, work:
import sequtils
proc foo[T](x: T): int = x + 1
proc foo[T: bool](x: T): int = -1
echo @[1, 2, 3].map(foo)