Hi. This may be a noble question.
I`d like to generate proc (OR func?) with different constant variable inside it, because the proc will be called frequently, avoiding to concatenate string on every call.
e. g)
import db_sqlite
template checkDoubleEdge(db:typed, table: string, s,t: typed): proc(db:DbConn, s,t: int): bool =
const query = "SELECT source FROM " & table & " WHERE source=? AND target=?;"
(db.getValue(sql(query), s, t)).len == 0
var db = open(":memory:","","","")
echo db.checkDoubleEdge("myedge",1,2)
This code result Error: type mismatch: got <bool> but expected 'template (db: DbConn, s: int, t: int): bool{.closure.}'
How can I fix it? or, What`s wrong with my understanding template.
Well, to start off - template is simple code substitution. You can't just return a "proc" from a template if you didn't actually made a proc. Second of all - if you want a template to generate a proc, it needs to have a name.
I really think that you can achieve what you want the simpler way - by using static[string], like here:
import db_sqlite
proc checkDoubleEdge(db: DbConn, table: static[string], s, t: int): bool =
const query = "SELECT source FROM " & table & " WHERE source=? AND target=?;"
result = (db.getValue(sql(query), s, t)).len == 0
var db = open(":memory:","","","")
echo db.checkDoubleEdge("myedge", 1, 2)
By marking an argument in a proc as static, you tell to the compiler that this argument should only accept arguments known at compile-time (like string literals)
an argument in a proc as static, you tell to the compiler that this argument should only accept arguments known at compile-time
Thank you. It worked and seems to be the thing I just want.
And about template, because its doing is a substitution, if I define const as another line inside it, I could not use it as a proc in my main code any more. Code substituted will be a statement. I guess.