Hi all!
I want to test out closures in Nim, so I wrote this code (you cat run it):
import sugar
proc calc(a: int, b: int): (int) -> int =
let diff = a - b
result = proc differentiate(c: int): int =
result = c - diff
let diff_proc = calc(5, 6)
echo diff_proc(7)
But instead of 8 got
Error: type mismatch: got <type proc> but expected 'proc (i0: int): int{.closure.}'
Why? Adding pragma do not help...
the error message could be better, but the problem is that a reguarly created proc (with name) is not a value.
There are two solutions:
proc calc(a: int, b: int): (int) -> int =
let diff = a - b
result = proc(c: int): int =
result = c - diff
or
proc calc(a: int, b: int): (int) -> int =
let diff = a - b
proc differentiate(c: int): int =
result = c - diff
differentiate
You need to provide an anonymous proc. This works:
import sugar
proc calc(a: int, b: int): (int) -> int =
let diff = a - b
result = proc (c: int): int =
result = c - diff
let diff_proc = calc(5, 6)
echo diff_proc(7)
The proc you want to return shouldn't have a name. So this line:
result = proc differentiate(c: int): int =
should be
result = proc (c: int): int =