Wasm Builders 🧱

Cover image for Compiling Grain with WASM
Kirtee Prajapati
Kirtee Prajapati

Posted on • Updated on

Compiling Grain with WASM

I won't wonder if you said you never heard of this language, ya that's because it's extremely latest, compact, and it's damn simple to understand.

Grain is a programming language that brings wonderful features from academic and functional programming languages to the 21st century.

One of the most exciting things about Grain is that it compiles to WebAssembly and can run in the browser, system, server.

Grain is strongly typed (with a type checker from OCaml), significantly reduces the need for type annotations.

Moving ahead let's set up the environment first.

  1. Install Grain Locally.

  2. Install Wasmtime for an Alternative/manual method visit the site or simply run this command regardless of your operating system. to execute the .wasm file.

curl https://wasmtime.dev/install.sh -sSf | bash
Enter fullscreen mode Exit fullscreen mode

Verify installation
wasmtime --version

Yuss! so with this you are all set to run your First Grain program.

  1. Program

Open your preferred text editor and make a file with the .gr extension. Grain recommends VS Code to work with .gr files.

Installation of grain extension for VS code is highly recommended.

The Fibonacci code in Grain is as follows :
Enter fullscreen mode Exit fullscreen mode
```
let rec fibonacci = (n) => {
  if (n == 0 || n == 1) {
    n
  } else {
    fibonacci(n - 1) + fibonacci(n - 2)
  }
}

print(fibonacci(7))
```
Enter fullscreen mode Exit fullscreen mode

We need to mention that a function is recursive with the keyword recin Grain.

Let's try something interesting! What about taking your Food orders

 enum Topping { Cheese, Pepperoni, Peppers, Pineapple }
 enum Order { Pizza(Topping), Calzone(Topping) }

 record Person { name: String, order: Order }

 let person = { name: "Steve", order: Calzone(Pepperoni) }

 match (person) {
 { order: Pizza(_), _ } => print("All pizzas are great here."),
 { order: Calzone(Peppers), _ } => print("Someone with great taste!"),
 { order: _, _ } => print("Yep, that's an order.")
}
Enter fullscreen mode Exit fullscreen mode
  1. Compiling the code To compile your Grain code, simply run :
  • For order.gr

    grain Order.gr
    

This would print Yep, that's an order. on your terminal and generate a Order.gr.wasm file.

  • For Fibonacci.gr

    grain fibonacci.gr
    

This would print 13 on your terminal and generate a fibonacci.gr.wasm file.

  1. Running .wasm file in Wasmtime

To run our .wasm file in wasmtime, run the following command
for Order.gr.wasm

wasmtime order.gr.wasm
Enter fullscreen mode Exit fullscreen mode

For Fibonacci.gr.wasm

wasmtime fibonacci.gr.wasm
Enter fullscreen mode Exit fullscreen mode

Image description

And you are good to go, this too will return the same output as above i.e. 13

References:
Enarx Docs for Wasm with Grain

Top comments (0)