Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
March 20, 2022 02:36 pm GMT

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}

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.


Original Link: https://dev.to/ducaale/binding-and-continuations-in-ml-5d3e

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To