5

I have the following Chapel code.

proc update(x: int(32)) {
  return 2*x;
}

proc dynamics(x: int(32)) {
  return update(x);
}

writeln(dynamics(7));

I would like to send some kind of callback to dynamics, like

proc update(x: int(32)) {
  return 2*x;
}

proc dynamics(x: int(32), f: ?) {
  return f(x);
}

writeln(dynamics(7, update));

Is this possible? Are there examples I could browse?

Brian Dolan
  • 3,086
  • 2
  • 24
  • 35

2 Answers2

6

Chapel has first-class functions . They are work in progress, at the same time have been used successfully (details are escaping me).

Your example works if you either remove the :? or specify the function's type as func(int(32), int(32)):

proc dynamics(x: int(32), f) // or proc dynamics(x: int(32), f: func(int(32), int(32)))

Vass
  • 431
  • 2
  • 4
  • 1
    Function objects are a reasonable alternative to first-class functions - make a record and define `proc this(args)` for it. `myRecord(args)` will call that. – mppf May 25 '20 at 17:16
1

The same intention may also get fulfilled with passing a lambdified "callback", potentially with an ALAP-associatively mapped callback-wrapper.

var f = lambda(n:int){ return -2 * n;};
writeln( f( 123 ) );                                        // lambda --> -246

proc update( x: int(32) ) {                                 // Brian's wish
  return 2*x;
}

proc dynamics( x: int(32), f ) {                            // Vass' solution
  return f( x );
}
// ---------------------------------------------------------------------------    
writeln( dynamics( 7, f ) );                                // proof-of-work [PASS] --> -14

var A = [ lambda( n:int ){ return 10 * n; },                // associatively mapped lambdified-"callbacks"
          lambda( n:int ){ return 20 * n; },
          lambda( n:int ){ return 30 * n; }
          ];
// ---------------------------------------------------------------------------    
writeln( dynamics( 8, lambda(i:int){ return    f(i); } ) ); // proof-of-work [PASS] --> -16
writeln( dynamics( 8, lambda(i:int){ return A[1](i); } ) ); // proof-of-work [PASS] -->  80
// ---------------------------------------------------------------------------
forall funIDX in 1..3 do
       writeln( dynamics( 8, A[funIDX] ) );                 // proof-of-work [PASS] -->  80 | 160 | 240

The whole TiO.run online-IDE mock-up code is here.

user3666197
  • 1
  • 6
  • 50
  • 92