http://www.adaic.org/resources/add_content/standards/05rat/html/Rat-3-4.html
from Ada, to get an idea about how easy it is to use nested functions as funargs in Nimrod.
import math
type
TFloatFunc1 = proc (x : Float) : Float {. closure .}
TFloatFunc2 = proc (x : Float, y : Float) : Float {. closure .}
proc integrate(f : TFloatFunc1,
lo : Float,
hi : Float,
n : Int) : Float =
result = 0.0
let dx : Float = (hi - lo) / toFloat(n)
for i in 0..n-1:
result += f(lo + toFloat(i) * dx) * dx
proc unitCircle(x : Float) : Float =
let x2 = x * x
if x2 < 1.0:
return sqrt(1.0 - x2)
else:
return 0.0
proc integrate(f : TFloatFunc2,
x0 : Float, x1 : Float,
y0 : Float, y1 : Float,
nx : Int, ny : Int) : Float =
proc f_y(y: Float) : Float =
proc f_x(x : Float) : Float = return f(x, y)
return integrate(f_x, x0, x1, nx)
return integrate(f_y, y0, y1, ny)
proc unitSphere(x : Float, y : Float) : Float =
var sum = x*x + y*y
if sum <= 1.0:
return sqrt(1.0 - sum)
else:
return 0.0
proc main() =
let result1 = integrate(unitCircle, -1.0, 1.0, 500)
echo("integrate(unitCircle, -1.0, 1.0, 500) = ", result1)
let result2 = integrate(unitSphere, -1.0, 1.0, -1.0, 1.0, 100, 100)
echo("integrate(unitSphere, -1.0, 1.0, -1.0, 1.0, 100, 100) = ", result2)
when isMainModule:
main()
While the 1D integrator works, the 2D integrator generates C code with an undeclared identifier and fails late in compilation. I've tried omitting the closure pragma, making f_x anonymous, and a few other things, but the problem persists. What do I have to do to fix this code?
I tried passing f explicitly, and renaming like the following (now ugly) code
proc integrate(f : TFloatFunc2,
x0 : Float, x1 : Float,
y0 : Float, y1 : Float,
nx : Int, ny : Int) : Float =
proc f_y0(f0: TFloatFunc2, y: Float) : Float =
proc f_x(x : Float) : Float = return f0(x, y)
return integrate(f_x, x0, x1, nx)
proc f_y(y: Float) : Float = return f_y0(f, y)
return integrate(f_y, y0, y1, ny)
and the same error now pops up with x0 as the undeclared ident. Should I submit a bug report? It seems you already know about this and want the language to support something like what I wrote in the first post.
I see, it's issue 581, https://github.com/Araq/Nimrod/issues/581
The example there is quite small and shows the problem clearly. Hopefully it will be easy to fix.