4

This syntax would be very useful—is there a reason for this not working? Thanks!

module Foo = {
  let bar: string = "bar"
};

let bar = Foo.bar; /* works */
let { bar } = Foo; /* Unbound record field bar */

Try it online!

Richard-Degenne
  • 2,892
  • 2
  • 26
  • 43
M. Walker
  • 603
  • 4
  • 14

2 Answers2

7

The closest you can do is something like this:

module Foo = {
  let bar = "bar";
  let baz = "baz";
};

let (bar, baz) = Foo.(bar, baz);
vkurchatkin
  • 13,364
  • 2
  • 47
  • 55
3

It is not possible to destructure a module in OCaml/Reason.

The equivalent OCaml code produces a syntax error on line 3

module Foo = struct let bar: string = "bar" end
let bar = Foo.bar
let struct bar end = Foo

File "", line 3, characters 4-10: Error: Syntax error

If you are OK with bringing all of the values specified in Foo into the local scope, then you can use open Foo. https://reasonml.github.io/try.html?reason=LYewJgrgNgpgBAMRCOBeOBvOsAucBGAhgE4BccAzjsQJYB2A5mnAERHEtwC+A3AFAgADjDqJk-AFIUAdFBAMAFOwCUQA

module Foo = { let bar: string = "bar" };
open Foo;
Js.log(bar)

If you also want to export all of the definitions in Foo through the current modules exports, you can include Foo. https://reasonml.github.io/try.html?reason=LYewJgrgNgpgBAMRCOBeOBvOsAucBGAhgE4BccAzjsQJYB2A5mnAERHEtwC+A3AFD0AxlAhh4SEPwBSFAHRQQDABTsAlEA

module Foo = { let bar: string = "bar" };
include Foo;
Js.log(bar)
barkmadley
  • 5,207
  • 1
  • 28
  • 31