Hello, Nim Community!
Few days ago I stumbled upon the **Nim Programming Language** and quickly have
fallen in love with it. It is beautiful and powerful! Mostly by trial and error
I figured out a way of defining named closures using block scope. But I am not
sure that my approach resulted in idiomatic Nim. May be a better or/and simpler
alternatives exist that evaded the beginner's attention. Anyway, here is my
code:
## Define a single closure within the block
let hello = block:
let greeting= "Hey, "
(proc (name: string): string =
result= greeting & name & "!"
)
doAssert hello("Nim") == "Hey, Nim!"
Run
In a similar way one can define several closures that share the same
environment
## Define two closures sharing the same environment within the block
let (hello, set_greeting) = block:
var greeting= "Hey, "
proc hello(name: string): string =
result= greeting & name & "!"
proc set_greeting(new_greeting: string): string =
result = greeting
greeting= new_greeting
(hello, set_greeting)
doAssert hello("Nim") == "Hey, Nim!"
doAssert set_greeting("HELLO, ") == "Hey, "
doAssert hello("NIM") == "HELLO, NIM!"
Run
Any comments & critique are highly appreciated!
Thanks,
\--Leo|
---|---