Docs / Language Manual / Lazy Values
Edit

You are currently looking at the v6.0 - v8.2 docs (Reason v3.6 syntax edition). You can find the latest manual page here.

(These docs are equivalent to the old BuckleScript docs before the ReScript rebrand)

Lazy Values

A lazy value represents a deferred computation which will automatically memoize the result on the first run, and then return the memoized result on any repeated execution.

This is useful for defining functions and expressions for complex procedures that always return the same value, for example:

  • Doing expensive DOM traversals over the same tree over and over again

  • Doing file system operations on a static set of files that won't change

  • Doing expensive requests to an API server that would always return the same data

A lazy value has a type of Lazy.t('a), where 'a is the return value of the computation. All its functionality is encapsulated with the globally available Lazy module.

Creating a lazy value

Lazy values are part of the language. You can either use the lazy keyword to create a lazy value from an expression...

Reason (Old Syntax)ML (Older Syntax)JS Output
// We only want getFiles to read the file system once,
// so we wrap it in a lazy value
let getFiles =
  lazy({
    Js.log("Reading dir");
    Node.Fs.readdirSync("./pages");
  });

// On the first call, the computation takes place
Lazy.force(getFiles)->Js.log;

// The second call will just return the already calculated files
Lazy.force(getFiles)->Js.log;

...or you can also wrap an existing function to make it lazy:

Reason (Old Syntax)ML (Older Syntax)JS Output
// Example for wrapping a function with 0 parameters
let getFiles = () => {
  Node.Fs.readdirSync("./pages");
};

// Here we wrap our function in the lazy value
let lazyGetFiles = Lazy.from_fun(getFiles);
Reason (Old Syntax)ML (Older Syntax)JS Output
// Example for wrapping a function with parameters
let doesFileExist = name => {
  Node.Fs.readdirSync("./pages")->Js.Array2.find(s => name === s);
};

// Here we use the lazy syntax again
// since we can't use Lazy.from_fun
let lazyDoesFileExist = lazy(doesFileExist("blog.re"));

Whenever we want to wrap a function unit => 'a, we use Lazy.from_fun, otherwise we use the lazy(expr) keyword to wrap an expression or a function with 1 or more arguments.

Force a lazy computation

Lazy values need to be explicitly executed to be able to return a value. Use the Lazy.forceto start the execution:

Reason (Old Syntax)ML (Older Syntax)JS Output
let computation = lazy(1);

// Returns 1
Lazy.force(computation);

It is also possible to use pattern matching to force a lazy value to compute, this includes switch expressions and similar syntax such as tuple destructuring:

Reason (Old Syntax)ML (Older Syntax)JS Output
// Extract a lazy value via pattern matching
let computation = lazy("computed");

switch computation {
| lazy("computed") => Js.log("ok")
| _ => Js.log("not ok")
};
Reason (Old Syntax)ML (Older Syntax)JS Output
// Destructuring a single value
// Note: currently the formatter will reprint this
//       as `let lazy word = ...`
let lazy(word) = lazy("hello");

// Output: "hello"
Js.log(word);
Reason (Old Syntax)ML (Older Syntax)JS Output
// Destructing a tuple
let lazyValues = (lazy("hello"), lazy("world"));
let (lazy(word1), lazy(word2)) = lazyValues;

// Output: "hello world"
Js.log2(word1, word2);
let lazy(word) = lazy("hello");

As you can see, the lazy syntax is a really great way for creating and handling lazy computations!

Exception handling

Whenever a lazy value computation raises an exception, the same exception will be thrown by Lazy.force.

Reason (Old Syntax)ML (Older Syntax)JS Output
let readFile =
  lazy({
    raise(Not_found)
  });

try (Lazy.force(readFile)) {
| Not_found => Js.log("No file")
};

Nothing new here, since we are using the try expression to match the exception raised in the lazy computation!

Please remember: Exceptions should be used sparsely!

Notes

A lazy value is not a shared data type. Don't rely on the runtime representation on the JS side.