How to implement a wrapper function that accepts any function?

I want to wrap some function inside an if:

let state = 1
let idOrNoop = (fn) => if state == 1 { fn } else { _ => () }

But it can only be applied to functions with single argument:

let foo = idOrNoop((a) => a+1)
let bar = idOrNoop((a, b) => a+b) // error

One possible solution I found is that I can make bar accepts a tuple instead of two arguments. Are there any other solutions? Or more generally, can I implement a function that accepts any function as input?

Rescript is strongly typed. The function returned inside else block has to be of same type as the one returned inside the if block. You can do something like below.

let state = 1
let idOrNoop = (idFn, noopFn) => state == 1 ? idFn : noopFn

let foo = idOrNoop(a => a + 1, _ => 0)
let bar = idOrNoop((a, b) => a + b, (_, _) => 0)
3 Likes