How to write local function which can be called from different levels

https://learninghub.kx.com/forums/topic/how-to-write-local-function-which-can-be-called-from-different-levels

Hi,

My code below works without error:

No Error

g:`;
g:{[xG] xG + 2}; // global; works for f and h
f:{[xF] 
h:{[xH] g[xH] + 3};
show g[xF] + h[xF];
}
f[40]; // i.e. 87; no error

 

However, I prefer a local g instead of a local one. I also tried below, but both failed:

Trial 1 (Failed)

g:`;
f:{[xF] 
g:{[xG] xG + 2}; // local; doesn't work for h
h:{[xH] g[xH] + 3};
show g[xF] + h[xF];
}
f[40]; // error

and

Trial 2 (Failed)

g:`;
f:{[xF] 
h:{[xH] g:{[xG] xG + 2}; g[xH] + 3}; // local; doesn't work for f
show g[xF] + h[xF];
}
f[40];// error

Is it possible to have a local g without an error? Thanks.

You could pass it in to a projection

 

q)f:{[xF] g:{[xG] xG + 2};
       h:{[g;xH] g[xH] + 3}[g];
       g[xF] + h[xF]} 
q)f[40] 
87

 

Or composition in this basic case

 

q)f:{[xF] g:{[xG] xG + 2};
        h:+[3] g @;
        g[xF] + h[xF]} 
q)f[40] 
87