Binding and continuations in ML
Mohamed Dahir
Posted on March 20, 2022
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
}
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
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)));;
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.
- https://www2.lib.uchicago.edu/keith/ocaml-class/definitions.html
- https://fsharpforfunandprofit.com/posts/computation-expressions-continuations/#continuations-and-let
- https://jobjo.github.io/2019/04/24/ocaml-has-some-new-shiny-syntax.html
- https://www.cs.cornell.edu/courses/cs3110/2015fa/l/17-async/rec.html
Posted on March 20, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024
November 29, 2024