816 search results for ""
-
Mutability and Imperative Control Flow
Dereference Operator
it is impossible to create uninitialised references, and the mutable content and the reference have different syntax and type: no confusion between them is possible. When working with mutable data in
Introduction -
Mutability and Imperative Control Flow
Mutable Record Fields
Remark : the left arrow symbol <- for mutating mutable record field values is not an operator function, like the assignment operator ( := ) is for refs . It is rather a construct of the langua
Introduction -
Mutability and Imperative Control Flow
Remark: References Are Single Field Records
create does the same as the ref function provided by the standard library. assign does the same as the ( := ) operator. deref does the same as the ( ! ) operator. The functions: Since ref
Introduction -
Mutability and Imperative Control Flow
Arrays
For a more detailed discussion on arrays, see the Arrays tutorial. the array location to update (when on the left-hand side of <- ), or the cell's content (when on the right-hand side of <- ). T
Introduction -
Mutability and Imperative Control Flow
Byte Sequences
<!-- FIXME: link to a dedicated Byte Sequences tutorial --> Note : the bytes type uses a much more compact memory representation than char array . As of writing this tutorial, there is an 8-fact
Introduction -
Mutability and Imperative Control Flow
Example: get_char Function
In the second call to tcsetattr , we restore the terminal attributes to their initial state. In this implementation, the record returned by the call to tcgetattr is not modified. A copy is made u
Introduction -
Mutability and Imperative Control Flow
Imperative Control Flow
OCaml allows you to evaluate expressions in sequence and provides for and while loops to execute a block of code repeatedly.
Introduction -
Mutability and Imperative Control Flow
Evaluating Expressions in Sequence
Names may be bound. In the example, no name is bound since () is used. Side effects take place in sequence. The bound expression ( print_string "This is" ) is evaluated first, and the referring exp
Introduction -
Mutability and Imperative Control Flow
Semicolon
Fun fact : begin … end and parentheses are literally the same: Remember the value of a semicolon-separated sequence is the value of its last expression. Grouping the first two steps with begi
Introduction -
Mutability and Imperative Control Flow
if … then … else … and Side Effects
Failing to group in the first branch results in a syntax error. What's before the semicolon is parsed as an if … then … without an else expression. What's after the semicolon appears as a da
Introduction -
Mutability and Imperative Control Flow
For Loop
Note: Here is how to do the same thing using an iterator function: for loops are convenient to iterate over and modify arrays: When you use the downto keyword (instead of the to keyword),
Introduction -
Mutability and Imperative Control Flow
While Loop
In this example, the while loop continues to execute as long as the value held by the reference i is less than 5 . The iteration executes the body expression as long as the condition remains tr
Introduction -
Mutability and Imperative Control Flow
Breaking Loops Using Exceptions
This while loop echoes characters typed on the keyboard. When the ASCII Escape character is read, the Exit exception is thrown, which terminates the iteration and displays the REPL reply: - :
Introduction -
Mutability and Imperative Control Flow
References Inside Closures
Calling c2 () increments the counter associated with c2 . Since c2 has its own independent counter, it starts at 0. Another call to c1 () increments its counter, resulting in 2. Calling c1 (
Introduction -
Mutability and Imperative Control Flow
Recommendations for Mutable State and Side Effects
Functional and imperative programming styles are often used together. However, not all ways of combining them give good results. We show some patterns and anti-patterns relating to mutable states and
Introduction -
Mutability and Imperative Control Flow
Good: Function-Encapsulated Mutability
The function sum is written in an imperative style, using mutable data structures and a for loop. However, no mutability is exposed. It is a fully encapsulated implementation choice. This functio
Introduction -
Mutability and Imperative Control Flow
Good: Application-Wide State
Note : Here, the state is copied, which is not memory efficient. In a memory-aware implementation, state-update functions would produce a “diff” (data describing the difference between the state'
Introduction -
Mutability and Imperative Control Flow
Good: Precomputing Values
However, it is possible to make a faster implementation by precomputing all the possible values in advance. There are only 256 of them, which you'll see listed after the first result below: Let'
Introduction -
Mutability and Imperative Control Flow
Good: Memoization
You can find a concrete example of memoization and an in-depth explanation in the chapter on Memoization of "OCaml Programming: Correct + Efficient + Beautiful." are found in the cache (it is a hi
Introduction -
Mutability and Imperative Control Flow
Good: Functional by Default
Most existing modules provide an interface meant to be used in a functional way. Some require the development and maintenance of wrapper libraries to be used in an imperative setting and such use r
Introduction -
Mutability and Imperative Control Flow
It Depends: Module State
On the other hand, a module may define mutable data internally impacting its behaviour without exposing it in its interface. This is inadvisable. For example, the Hashtbl module provides an inte
Introduction -
Mutability and Imperative Control Flow
Bad: Undocumented Mutation
<!-- TODO: ### Bad: Stateful External Factor GOTCHA: This is the dual of the previous anti-pattern. “Mutable in disguise” is an unintended or undocumented side-effect performed by a function.
Introduction -
Mutability and Imperative Control Flow
Bad: Undocumented Side Effects
If you're writing functions with non-obvious side effects, don't shadow existing definitions. Instead, give the function a descriptive name (for instance, Array.copy_with_analytics ) and document th
Introduction -
Mutability and Imperative Control Flow
Bad: Side Effects Depending on Order of Evaluation
<!-- You can use the sequence operator `;` to execute expressions in a particular order: ```ocaml # print_endline "ha"; print_endline "ho";; ha ho - : unit = () ``` `let` expressions are executed in
Introduction -
Mutability and Imperative Control Flow
Conclusion
A mutable state is neither good nor bad. For the cases where a mutable state enables a significantly simpler implementation, OCaml provides fine tools to deal with it. We looked at references, mutabl
Introduction -
Modules
Modules
Introduction
Note : The files that illustrate this tutorial are available as a Git repo . Modules are collections of definitions grouped together. This is the basic means to organise OCaml software. Separate co
Module SystemModules
Basic Usage
Module SystemModules
File-Based Modules
In a project, it is preferable to create the dune configuration files and directory structure using the dune init project command. Refer to the Dune documentation for more on this matter. Ac
Module SystemModules
Naming and Scoping
The module access notation can be applied to an entire expression: You can open a module inside a definition, using the let open ... in construct: The standard library is a module called Std
Module SystemModules
Interfaces and Implementations
This triggers a compilation error. You can check that Cairo.message is not public by attempting to compile a delhi.ml file containing: Compile and execute both programs: Update the dune
Module SystemModules
Abstract and Read-Only Types
Abstract and read-only types can be either variants, as shown in this section, records, or aliases. It is possible to access a read-only record field's value, but creating such a record requires usin
Module SystemModules
Submodules
Module SystemModules
Submodule Implementation
dune Definitions from a submodule are accessed by chaining module names, here Florence.Hello.print . Here is the updated dune file, with an additional executable: glasgow.ml florence.ml
Module SystemModules
Submodule With Signatures
The first version made Florence.Hello.message public. In this version it can't be accessed from glasgow.ml . To define a submodule's interface, we can provide a module signature . This is do
Module SystemModules
Module Signatures are Types
This allows writing interfaces shared by several modules. An implementation satisfies any module type listing some of its contents. This implies a module may have several types and that there is a su
Module SystemModules
Module Manipulation
Module SystemModules
Displaying a Module's Interface
If you are using Dune, .cmi file are in the _build directory. Otherwise, you can compile manually to generate them. The command ocamlc -c cairo.ml will create cairo.cmo (the executable byteco
Module SystemModules
Module Inclusion
It creates a module Extlib.List that has everything the standard List module has, plus a new uncons function. In order to override the default List module from another .ml file, we need
Module SystemModules
Stateful Modules
Values returned by Random.bits will differ when you run this code. The first and third calls return the same results, showing that the internal state was reset. A module may have an internal
Module SystemModules
Conclusion
Functors, which act like functions from modules to modules Libraries, which are compiled modules bundled together Packages, which are installation and distribution units Going further, here are the o
Module SystemFunctors
Functors
Introduction
Note : The files illustrating this tutorial are available as a Git repo . As suggested by the name, a functor is almost like a function. However, while the inputs and outputs of functions are val
Module SystemFunctors
Project Setup
Check that this works using the opam exec -- dune exec funkt command. It shouldn't do anything (the empty file is valid OCaml syntax), but it shouldn't fail either. The stanza libraries str makes
Module SystemFunctors
Using an Existing Functor: Set.Make
There are no duplicates in a Set . Therefore, the string "funkt" is only displayed once, although it appears twice in the dune file. The functions StringSet.of_list and StringSet.iter are
Module SystemFunctors
Extending a Module with a Standard Library Functor
This allows the user to seemingly extend the module String with a submodule Set . Check the behaviour using opam exec -- dune exec funkt < dune . funkt.ml Using the include statement, here i
Module SystemFunctors
Parametrising Modules with Functors
Module SystemFunctors
Functors From the Standard Library
Set.S Map.S Hashtbl.S The functors Set.Make , Map.Make , and Hashtbl.Make return modules satisfying the interfaces Set.S , Map.S , and Hashtbl.S (respectively), which all contain an abstract
Module SystemFunctors
Writing Your Own Functors
Here is the skeleton of a possible implementation: Heap implementations can be represented as functors from OrderedType into HeapType . Each kind of heap would be a different functor. Using su
Module SystemFunctors
heap.ml
<!-- TODO: Create this section When several implementations of the same interface are needed at runtime, functors allow sharing of their common parts. ## Multiple Implementation of the Same Signat
Module System