Reason
  • Docs
  • Try
  • API
  • Community
  • Blog
  • Languages iconEnglish
    • 日本語
    • Deutsch
    • Español
    • Français
    • 한국어
    • Português (Brasil)
    • Русский
    • Українська
    • 中文
    • 繁體中文
    • Help Translate
  • GitHub

›Language Basics

Intro

  • What & Why
  • Getting started

Setup

  • Installation
  • Editor Plugins
  • Format (refmt)

Language Basics

  • Overview
  • Let Bindings
  • Primitives
  • Basic Structures
  • Types
  • Records
  • Variants
  • Options and nullability
  • Functions
  • Recursion
  • Destructuring
  • Pattern Matching
  • Mutable Bindings
  • Loops
  • Modules

Advanced Features

  • JSX
  • External
  • Exception
  • Object

JavaScript

  • Melange
  • Interop
  • Syntax Cheatsheet
  • Pipe First
  • Promise
  • Libraries
  • Converting from JS

Extra

  • Frequently Asked Questions
  • Extra Goodies
  • REPL (rtop)
Edit

Mutable Bindings

Quick overview: Refs

Refs allow mutable bindings in your program. They are a thin wrapper around a record with a mutable field called contents.

type ref('a) = {
  mutable contents: 'a,
};

There is syntax built into the language to work with ref structures.

  • ref(value) creates a ref with contents as value
  • x^ accesses the contents of the ref x
  • x := updates the contents of the ref x
let x = ref(10);
x := x^ + 10;
x := x^ + 3;
/* x^ is 23 */

If you prefer to avoid the ref syntax the following code is exactly equivalent to the syntax above:

let x = {contents: 10};
x.contents = x.contents + 10;
x.contents = x.contents + 3;
/* x.contents is 23 */

Note: Make sure you need mutable bindings before using them. The trivial example above should not use mutable bindings and instead should use: Binding Shadowing

← Pattern MatchingLoops →