Variables and functions are fundamental ideas that show up in virtually all programming languages. OCaml has a different take on these concepts than most languages you’re likely to have encountered, so this chapter will cover OCaml’s approach to variables and functions in some detail, starting with the basics of how to define a variable, and ending with the intricacies of functions with labeled and optional arguments.
Don’t be discouraged if you find yourself overwhelmed by some of the details, especially toward the end of the chapter. The concepts here are important, but if they don’t connect for you on your first read, you should return to this chapter after you’ve gotten a better sense for the rest of the language.
At its simplest, a variable is an identifier whose meaning is bound
to a particular value. In OCaml these bindings are often introduced using
let keyword. We can type a
let binding with the following syntax. Note that
variable names must start with a lowercase letter or an
As we’ll see when we get to the module system in Chapter 4, this same syntax is used for
bindings at the top level of a module.
Every variable binding has a scope, which is
the portion of the code that can refer to that binding. When using
utop, the scope of a top-level
let binding is everything that follows it in the session. When it shows up in a module, the scope is the remainder of that ...