Callback functions in Chapel
Asked Answered
C

2

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?

Colson answered 23/5, 2020 at 0:59 Comment(0)
R
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)))

Rufe answered 23/5, 2020 at 2:51 Comment(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.Bakeman
E
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.

Expressionism answered 23/5, 2020 at 10:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.