DEV Community

Mohamed Dahir
Mohamed Dahir

Posted on

Binding and continuations in ML

If you have ever worked with Rust code before, you might have come across code like this

let a = {
  let x = 5;
  let y = 4;
  let x = 7;
  x + y
}
Enter fullscreen mode Exit fullscreen mode

Considering your past experience with C-based language, several questions might spring to mind:

  • Why is it legal to define the same variable multiple times?
  • Why do blocks evaluate to the last expression in their bodies?

To get answers and more, It helps to look at a distant cousin to Rust.

Enter OCaml

NB: You can refer to https://learnxinyminutes.com/docs/ocaml/ for a quick crash course on OCaml's syntax

The same code in OCaml would be written like this:

let a =
  let x = 5 in
  let y = 4 in
  let x = 7 in
  x + y
Enter fullscreen mode Exit fullscreen mode

Which could be viewed as syntactic sugar for the following:

(* bind is a Higher-order function that takes a value and
 * a function, and returns the result of applying that value
 * to the function
 *)
let bind x fn = fn x;;

bind 5 (fun x ->
  bind 6 (fun y ->
    bind 7 (fun x ->
      x + y
    )
  )
);;

(* Same code but without indentation.
 * Notice how bind has replaced the assignment operator.
 *)
bind 5 (fun x ->
bind 6 (fun y ->
bind 7 (fun x ->
x + y)));;
Enter fullscreen mode Exit fullscreen mode

Because each line in our first OCaml snippet corresponds to a nested function in our second snippet, we can see why it is legal to define the same variables multiple times. It also shows why blocks are just expressions that evaluate to the last value in their bodies.

Killing all birds with one stone

Replacing the assignment operator with a customizable bind function is a powerful abstraction that lets us do all sorts of things that would otherwise have taken years to be implemented in the core language, including Rust's try operator and async/await syntax.

While I won't bore you with all the details of how this is done, I will leave you with some resources if you're interested in how deep the rabbit hole goes.

Top comments (0)