The BasicsEdit on GitHub
In this section, we’ll learn how to declare new bindings and perform some basic operations on them.
Declaring Named Values
Grain uses the
let keyword to introduce new values with a given name, which we call bindings. Here are some examples using primitive types:
We can reference bindings we’ve created in Grain to form compound expressions:
Working with Tuples
Tuples in Grain allow you to bundle up a few pieces of data. They’re great for related, uniform data. Mixed data types are allowed within tuples, and we’ll take advantage of that in this example. Here’s an example of a tuple containing a user’s name, age, and favorite color:
Grain supports tuple destructuring to pull data out of tuples:
// The same tuple from the previous example
Since we only care about some of the values in this tuple, we can use underscores instead of names, and Grain will not create bindings for those fields.
// The same tuple from the previous two examples
Other Basic Operations
You may find some of these useful throughout your Grain programs.
The standard number operations include addition, subtraction, multiplication, division, and modulus (remainder). If you’re looking for more number operations, you may find what you’re looking for in the
let sum = 2 + 2 // 4
These operators return a boolean result of
false. In this example, every statement returns
== to check equality.
== checks for structural equality, so it also works for comparing things like tuples and lists.
The classic booleans operators
! are available.
if statement in Grain always returns a value. For this reason, our
if statements must always have an
else branch. The last value in the block is the value of the statement.