0

Suppose that we have an object which has some properties of type proc:

type
    x = object
        y: proc(a,b:int)

proc myproc(a,b:int) =
    echo a

var tmp = new x
tmp.y = myproc # I want to insert initial value in this line for example a = 1

tmp.y(5)

How can I insert initial values in the specified line, and not anywhere else? Thank you in advance

Shoaib Mirzaei
  • 512
  • 4
  • 11

1 Answers1

2

As far as I know it's not possible to do what you want without other modifications, because you have specified y to be a proc receiving two parameters. So whatever you assign to it, the compiler is always going to expect you to put two parameters at the call site.

One alternate approach would be to use default values in the proc definition:

type
    x = object
        y: proc(a: int = 1, b: int)

proc myproc(a,b: int) =
    echo(a, " something ", b)

var tmp = new x
tmp.y = myproc

tmp.y(b = 5)

The problems with this solution are of course that you can't change the value of a at runtime, and you are forced to manually specify the name of the parameter, otherwise the compiler is going to presume you are meaning the first and forgot to specify b. Such is the life of a non dynamic language.

Another approach is to define the proc as having a single input parameter, and then using an anonymous proc or lambda to curry whatever values you want:

type
    x = object
        y: proc(a: int)

proc myproc(a,b: int) =
    echo(a, " something ", b)

var tmp = new x
tmp.y = proc (x: int) = myproc(1, x)

tmp.y(5)

If you were to use the sugar module, as suggested in the docs, the assignment line could look like:

tmp.y = (x: int) => myproc(1, x)
Grzegorz Adam Hankiewicz
  • 7,349
  • 1
  • 36
  • 78
  • Thank you Mr Hankiewicz. I have some variables of the same type but different first argument. I just changed the way of coding and instead of doing it inside `type`, I defined a proc with the first parameter of the same type then each time, I used that proc I could change first argument accordingly. Thank you again. – Shoaib Mirzaei Jun 13 '22 at 10:14