Seneca
Seneca

Reputation: 2412

OCaml dynamic function name

I have a list of tags:

let tags = ["div", "h1", "p"]

Can I generate a module which contains functions with those tags as names?

/* don't mind the syntax, it's Facebook's Reason (new interface to ocaml) */

let module DOM = {
   let div props children => Js.Unsafe.fun_call
        (Js.Unsafe.get dom (Js.string "div")) [|Js.Unsafe.inject props, Js.Unsafe.inject children|];
    let h1 props children => Js.Unsafe.fun_call
        (Js.Unsafe.get dom (Js.string "h1")) [|Js.Unsafe.inject props, Js.Unsafe.inject children|];
let p props children => Js.Unsafe.fun_call
        (Js.Unsafe.get dom (Js.string "p")) [|Js.Unsafe.inject props, Js.Unsafe.inject children|];

}

The tag name should become a function in the module... Is this possible?

Upvotes: 0

Views: 342

Answers (1)

camlspotter
camlspotter

Reputation: 9030

Assuming what you want to do is to build a module with names from a string list while program execution,

Short answer: No, OCaml is a static typed language and you cannot build a new variable name while program execution.

Longer answer: you could use meta-programming: build a source code with names your want then compile it and dynamically link the compiled module. But this is not a regular way of using OCaml at all. In addition, looking at your environment, OCaml (or Reason) to output Js code, you likely need to have an OCaml (or Reason) compiler compiled to Js, which is hard and should be avoided.

Conclusion: No, you cannot.

Upvotes: 4

Related Questions