The Basics
Edit on GitHubIn 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:
1 | // 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.
1 | // The same tuple from the previous two examples |
Other Basic Operations
You may find some of these useful throughout your Grain programs.
Number Operations
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 Math
module.
1 | let sum = 2 + 2 // 4 |
Number Comparisons
These operators return a boolean result of true
or false
. In this example, every statement returns true
.
Equality
Use ==
to check equality. ==
checks for structural equality, so it also works for comparing things like tuples and lists.
Boolean Operations
The classic booleans operators &&
, ||
, and !
are available.
The if
Statement
The 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.