It seems a little weird for Nim to make these procs and then set special rules, preventing you from passing them in as parameters to other procs.
proc someHigherOrderProc(fn: proc(x, y: int): int) =
discard
someHigherOrderProc(`+`)
has to become:
proc someHigherOrderProc(fn: proc(x, y: int): int) =
discard
someHigherOrderProc(proc(x, y: int) = x + y)
which needlessly makes the code more messy.I don't have an answer to your question, but use
import sugar
proc someHigherOrderProc(f: (int, int) -> int) =
discard
someHigherOrderProc((x, y) => x + y)
for less mess
+ etc aren't really procs, i mean, in C terms you can't have a function pointer to + unless you go ahead and define an addition function.
templates are perfect for passing expressions around (the way mapIt, filterIt etc do) that might be a better fit for what you're trying to do, without adding the overhead of a function call
in C terms you can't have a function pointer to +
I guess that makes sense, and it would definently be a needless performance hit to create a function just for this edge case.
templates are perfect for passing expressions around
I'm sorta new to Nim and metaprogramming, so I didn't think about using a template. Here is the code that inspired the question, but I don't really see how I would refactor it to utilize a template.
+ etc aren't really procs, i mean, in C terms you can't have a function pointer to + unless you go ahead and define an addition function.
Couldn't they be defined with something like {.inline.} in Nim? So it will be used as a normal proc in Nim but the C code will be generated as a + b?
Couldn't they be defined with something like {.inline.} in Nim?
The compiler could do things like that, yes. But features start in the state "not implemented" and there are many things left to do that are more important. Esp. since the alternative via templates works really well.
at first approximation templates are like c macros, (without the footguns). they can for sure get complicated, but at a high level, it's copy/paste.
so without the
{.gensym.}
you get a redefinition error, because you define a proc
for addition, then a second proc, also called
for subtraction...
{.gensym.}
tells the template to generate a unique symbol each time. "fn_gensym3" or whatever
another way to do the same thing is to wrap it in a
:
template operation(op:untyped):proc() =
block:
proc fn() = discard
fn