How to implement a shim?

Hello,

 

In general, how does one add to an already existing function’s definition? 

For example, suppose we define the identity function:

f:{x}

And that we wanted f to output one more than it currently does. 

f:{f+1}

The above wouldn’t work; this produces a stack error. 

'stack [1799f:{f+1}

I’m not sure how to redefine a function while referencing its current version and not causing such an error.

 

I acknowledge for this simple example, one could just redefine f:{x+1}. But the idea is to build on the existing f - not to destroy f and recreate it from scratch. That would be a redefinition, not a shim. If anything else may be unclear about my question, please let me know. 

 

Any help or advice would be greatly appreciated.

 

Kind regards,

Michael

Save the original definition to another variable and call that at the end of the redefinition as follows:

 

q)f 5 5 q)f_orig:f q)f:{f_orig x+1} q)f 5 6

 

Or alternatively you could use a projection:

 

q)f:{x} q)f 5 5 q)f:{x y+1}[f;] q)f 5 6

 

Note - these methods only allow additional handling to the input to the original function.

 

Thank you David!

Best regards,

Michael

Just for fun two more concepts to introduce:

  • Composition using @ allows you to chain a sequence of functions
  • value can be passed a symbol variable name and will return it’s contents

 

q)f:{x} q)f:value[`f] +[1] @ q)f {x}@[+[1]] q)f 1 2