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:
1 | module Main |
Grain uses type inference to automatically determine the type of values throughout your program. Even though in the above example we did not explicitly define the type of each binding, Grain deduced them automatically based on context. It is also possible to explicitly specify the types of binding:
1 | module Main |
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 | module Main |
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 | module Main |
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 Number
module.
1 | module Main |
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.
Block expressions
Block expressions allow you to group several expressions together to be executed one after another: to write a block expression surround several expressions with curly braces. The block expression as a whole will evaluate to its last expression’s value. For example: