Today I Learned

A Hashrocket project

Variadic args in ReasonML with JS Interop

I have this Javascript function in my utils file.

const add = (...args) => { return args.reduce((x, a) => a + x, 0) }

export add;

I’d like to use it in my ReasonML program, but it has variadic arguments, and ReasonML is a typed language. As long as all the variadic arguments are of the same type, however, I can import it into ReasonML with the [@bs.splice] attribute.

[@bs.module "utils"] [@bs.splice] external add : (array(int)) => int = "add";

[@bs.splice] will transform the last argument from an array into a list of arguments.

In ReasonML

let a = add([|1, 2, 3|]);

In Javascript

var a = add(1, 2, 3);