Here you go: 
[https://play.nim-lang.org/#ix=26DP](https://play.nim-lang.org/#ix=26DP), just 
one extra line and your code works.

The way this work is that templates are a way to insert premade AST into a 
specified location, which means:
    
    
    template cmpTaskField*(fieldName: untyped): untyped =
      proc cmp(task1, task2: Task): int = cmp(task1.fieldName, task2.fieldName)
    
    tasks = sorted(tasks, cmp = cmpTaskField(isComplete))
    
    
    Run

generates:
    
    
    tasks = sorted(tasks, cmp = proc cmp(task1, task2: Task): int = 
cmp(task1.fieldName, task2.fieldName))
    
    
    Run

and this is **not** valid Nim, because a named `proc` definition is a statement 
rather than an expression.

But the anonymous proc syntax `proc () =` does not work inside templates, so 
how can this be done? The answer is to define a proc then "return" its symbol:
    
    
    template cmpTaskField*(fieldName: untyped): untyped =
      proc cmp_custom(task1, task2: Task): int {.gensym.} = 
cmp(task1.fieldName, task2.fieldName)
      cmp_custom # <--- that's the proc (task1, task2: Task): int that we need
    
    
    Run

The reason why I renamed `cmp` into `cmp_custom` is so that the compiler could 
know exactly which `cmp` are we targeting.

Reply via email to