How can I use function pointers in Nimrod?
Asked Answered
P

1

8

Is it possible to use function pointers in Nimrod?

What I've tried is:

type fptr = (proc(int):int)

proc f(x:int): int = 
  result = x+1

var myf : fptr = f

echo myf(0)

but when I try to compile I get:

Hint: added path: 'C:\Users\Peter\.babel\pkgs\' [Path]
Hint: used config file 'C:\Program Files (x86)\Nimrod\config\nimrod.cfg' [Conf]
Hint: system [Processing]
Hint: hello3 [Processing]
Error: internal error: GetUniqueType
Traceback (most recent call last)
nimrod.nim               nimrod
nimrod.nim               handleCmdLine
main.nim                 mainCommand
main.nim                 commandCompileToC
modules.nim              compileProject
modules.nim              compileModule
passes.nim               processModule
passes.nim               processTopLevelStmt
cgen.nim                 myProcess
ccgstmts.nim             genStmts
ccgexprs.nim             expr
ccgstmts.nim             genStmts
ccgexprs.nim             expr
ccgstmts.nim             genVarStmt
ccgstmts.nim             genSingleVar
cgen.nim                 assignGlobalVar
ccgtypes.nim             getTypeDesc
ccgtypes.nim             getTypeDescAux
ccgtypes.nim             genProcParams
cgen.nim                 fillLoc
ccgutils.nim             getUniqueType
msgs.nim                 internalError
msgs.nim                 rawMessage
msgs.nim                 rawMessage
msgs.nim                 handleError
Ponzo answered 5/5, 2014 at 18:53 Comment(0)
L
9

Sure you can use pointers, the only problem is that you forgot to define the name of the first parameter and unfortunately this crashes the compiler. The following example works:

type fptr = (proc(x: int):int)

proc f(x:int): int = 
  result = x+1

var myf : fptr = f

echo myf(0)

Note that you can omit the type in the myf variable declaration. You can also omit the brackets around the proc type definition. I've reported the error you found to the developers at https://github.com/Araq/Nimrod/issues/1183.

Liesa answered 5/5, 2014 at 22:8 Comment(1)
You can also use the new proc type syntax. Just import the future module and replace (proc(x: int):int) with (int -> int).Subtreasury

© 2022 - 2024 — McMap. All rights reserved.