Search code examples
rascal

How to do 'function pointers' in Rascal?


Does Rascal support function pointers or something like this to do this like Java Interfaces?

Essentially I want to extract specific (changing) logic from a common logic block as separate functions. The to be used function is passed to the common block, which then call this function. In C we can do this with function pointers or with Interfaces in Java.

First I want to know how this general concept is called in the language design world.

I checked the Rascal Function Helppage, but this provide no clarification on this aspect.

So e.g. I have:

int getValue(str input) { 
 .... } 

int getValue2(str input){ 
  ... } 

Now I want to say:

 WhatDatatype? func = getValue2; // how to do this?

Now I can pass this to an another function and then:

 int val = invoke_function(func,"Hello"); // how to invoke?, and pass parameters and get ret value

Tx,

Jos


Solution

  • This page in the tutor has an example of using higher-order functions, which are the Rascal feature closest to function pointers:

    http://tutor.rascal-mpl.org/Rascal/Rascal.html#/Rascal/Concepts/Functions/Functions.html

    You can define anonymous (unnamed) functions, called closures in Java; assign them to variables; pass them as arguments to functions (higher-order functions); etc. Here is an example:

    rascal>myfun = int(int x) { return x + 1; };
    int (int): int (int);
    
    rascal>myfun;
    int (int): int (int);
    
    rascal>myfun(3);
    int: 4
    
    rascal>int applyIntFun(int(int) f, int x) { return f(x); }
    int (int (int), int): int applyIntFun(int (int), int);
    
    rascal>applyIntFun(myfun,10);
    int: 11
    

    The first command defines an increment function, int(int x) { return x + 1; }, and assigns this to variable myfun. The rest of the code would work the same if instead this was

    int myfun(int x) { return x + 1; }
    

    The second command just shows the type, which is a function that takes and returns int. The third command calls the function with value 3, returning 4. The fourth command then shows a function which takes a function as a parameter. This function parameter, f, will then be called with argument x. The final command just shows an example of using it.