638 search results for ""
-
Introduction to opam Switches
Listing Switches
The command below will display the opam switches that are configured on your system. After completing installation of OCaml, such as outlined in Installing OCaml , a single switch called default
Tooling -
Basic Data Types and Pattern Matching
Records
Note that records behave like single constructor variants. That allows pattern matching on them. To construct a new record with some field values changed without typing in the unchanged fields w
Introduction -
OCaml Programming Guidelines
Consistency of Indentation
Choose a generally accepted style of indentation, then use it systematically throughout the whole application.
Resources -
OCaml Programming Guidelines
match or try
Justification : The keyword with on its own line shows that the program enters the pattern-matching part of the construct. <!-- $MDX skip --> Put the keyword with at the end of the line. I
Resources -
Lists
The Standard Library List Module
In the List module documentation, functions which can raise an exception are marked. Such exceptions are usually the result of lists which are empty (and therefore have neither a head nor a tai
Introduction -
Higher Order Functions
Mapping Results
Both of these are useful in different situations, such as wanting to change the type of errors, or only perform operations once we have an Ok value. We can map the value in the Ok value constr
Introduction -
Libraries With Dune
Libraries
Dune creates a module Wmo from the contents of directory lib . The directory's name (here lib ) is irrelevant. The library name appears uncapitalised ( wmo ) in dune files: In its definition, i
Module System -
OCaml Programming Guidelines
Write Simple and Clear Programs
Reread, simplify, and clarify at every stage of creation. Use your head!
Resources -
Operators
Defining Binary Operators
It is a recommended practice to define operators in two steps, like shown in the example. The first definition contains the function's logic. The second definition is merely an alias of the first one
Advanced Topics -
Higher Order Functions
Uncurrying
But we can also uncurry our greet function to operate over the entire tuple! If we wanted to do something with any of these elements, we'd need to split the tuple, and call a function: Take
Introduction -
Values and Functions
Same-Level Shadowing
There are now two definitions of h in the environment. The first h is unchanged. When the second h is defined, the first one becomes unreachable. Another kind of shadowing takes place when t
Introduction -
A Tour of OCaml
Variant Types
As previously shown, sum , length , and map functions provide examples of pattern matching over the list variant type. Like a function, a variant can be recursive if it refers to itself in its
First Steps -
Transitioning to Multicore with ThreadSanitizer
Following the Workflow
We will now go through the proposed workflow for our example application.
Guides -
Error Handling
Assertions
Here, it wouldn't be correct to use failwith because it requires a corrupted system or the compiler to be bugged for the second code path to be executed. Breakage of the language semantics qual
Guides -
Basic Data Types and Pattern Matching
Tuples
<!--FIXME :: Please ensure this is still correct. In trying to keep examples away from a, b, c (so as not to be confused with `a, `b, `c), I thought it was particularly important here because the use
Introduction -
OCaml Programming Guidelines
for loops
Justification : The recursive function lets you code any loop whatsoever simply, even a complex one, e.g., with multiple exit points or with strange index steps (steps depending on a data value
Resources -
Debugging
Using the Debugger Under Emacs
Under Emacs you call the debugger using ESC-x ocamldebug a.out . Then Emacs will send you directly to the file and character reported by the debugger, and you can step back and forth using ES
Guides -
Configuring Your Editor
Finer configuration
OCaml-eglot can be finely configured, the project README gives several configuration paths to adapt perfectly to your workflow. You will also find there an exhaustive presentation of the different
Tooling -
Profiling
Using perf on Linux
The first command launches foo.native with arguments a b c d and records profiling information in perf.data ; the second command starts an interactive program to explore the call graph. The
Guides -
Higher Order Functions
Mapping Options
Note that both sides of the match return the same thing: if we had a None we return None , if we have a Some we return a Some . This way, the structure is preserved. Mapping an optional valu
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 -
Memoization
Fibonacci
Although this code uses imperative constructs (specifically, array update), the side effects are not visible outside the function fibm . So from a client's perspective, fibm is functional. The
Data Structures -
Sequences
Sequences for Conversions
Similar functions are also provided for sets, maps, hash tables ( Hashtbl ), and others. When implementing a datatype module, it is advised to expose to_seq and of_seq functions. Lists Ar
Data Structures -
Lists
Higher Order Functions on Lists
Notice the type of the function f in parentheses as part of the whole type. This map function, given a function of type 'a -> 'b and a list of 'a s, will build a list of 'b' s. Sometime
Introduction -
Basic Data Types and Pattern Matching
Strings
Operations on string values are provided by the Stdlib and the String modules. Indexed access to string characters is possible using the following syntax: <!--CR I'm not sure how to rearran
Introduction -
OCaml Programming Guidelines
Opening modules
<!-- $MDX skip --> Justification : The use of unqualified identifiers is ambiguous and gives rise to difficult-to-detect semantic errors. Avoid open directives, using instead the qualified
Resources -
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 -
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 -
Installing OCaml
Check Installation
Exit UTop by typing #quit;; or pressing Ctrl+D . Congratulations ! You've installed OCaml! 🎉 You're now in an OCaml toplevel, and you can start typing OCaml expressions. For instance, try t
First Steps -
Lists
Lists and Tail Recursion
In the standard library documentation, functions which are not tail-recursive are marked. Or, we can do it all in one function: We call such a function tail-recursive . We may write a wrappe
Introduction -
OCaml Programming Guidelines
How to Write Lists
Write x :: l with spaces around the :: (since :: is an infix operator, hence surrounded by spaces) and [1; 2; 3] (since ; is a delimiter, hence followed by a space).
Resources -
Basic Data Types and Pattern Matching
Booleans
Conditional expression and pattern matching on a Boolean are the same: The test subexpression must have type bool . Branches subexpressions must have the same type. In OCaml, if … then …
Introduction -
Basic Data Types and Pattern Matching
Lists
In the above expressions, [1; 2; 3] is the value that is matched over. Each expression between the | and -> symbols is a pattern. They are expressions of type list , only formed using [] , :
Introduction -
Basic Data Types and Pattern Matching
Arrays
Operations on arrays are provided by the Array module. There is a dedicated tutorial on Arrays . The left-arrow <- is the array update operator. Above, it means the cell at index 2 is set to va
Introduction -
Higher Order Functions
Currying
But we can also curry our reveal function to take 2 arguments! If we wanted to use reveal on a name, we have to put it into a tuple, and then do the call. Like this: Take for example this
Introduction -
Preprocessors and PPXs
Using PPXs
And that's all you need to use PPXs! Although these instructions will work for most PPXs, note that the first source of information will be the package documentation, as some PPXs might need some
Advanced Topics -
OCaml Programming Guidelines
How Much to Indent
The change in indentation between successive lines of the program is generally 1 or 2 spaces. Pick an amount to indent and stick with it throughout the program.
Resources -
Options
Exceptions vs Options
See Error Handling for a longer discussion on error handling using options, exceptions, and other means. The function Sys.getenv : string -> string from the OCaml standard library queries the
Data Structures -
Debugging
Limitations
Compiler builtins are described in the standard library documentation. At compile time, the __LOC__ builtin is substituted with its location in the program, described as a string "File %S, l
Guides -
A Tour of OCaml
Pairs and Tuples
The type of tuples is written using * between the components' types. Note: The function snd is predefined in the OCaml standard library. Access to the components of tuples is done using patte
First Steps -
Formatting and Wrapping Text
Boxes
within a “h” box: within a “v” box: within a “hv” box: If there is enough room to print the box on the line: But "---b---b---" that cannot fit on the line is written within a
Tutorials -
Higher Order Functions
Mapping Lists
Note how we use the :: constructor to both deconstruct the list and reconstruct it. The main difference is that instead of throwing away the resulting value from running our function over the el
Introduction -
Values and Functions
Pattern Matching on Records
We can pattern match on records: <!--Because records are implicitly single-constructor variants,-->
Introduction -
Profiling
Profiling Tools
After running the program as normal, the profiling code dumps out a file gmon.out which we can interpret with gprof : We compile it using the -p option to ocamlopt which tells the compil
Guides -
Debugging
Tracing Functions Calls in the Toplevel
The simplest way to debug programs in the toplevel is to follow the function calls, by “tracing” the faulty function:
Guides -
Debugging
Getting Help and Info in the Debugger
To get more info about the current status of the debugger you can ask it directly at the toplevel prompt of the debugger; for instance:
Guides -
A Tour of OCaml
Using the result Type
So one may write: Another way to deal with errors in OCaml is by returning value of type result , which can represent either the correct result or an error. Here is how it is defined:
First Steps -
Debugging
Launching the Debugger
Then the debugger answers with a banner and a prompt: We launch the debugger: At runtime, the program raises an uncaught exception Not_found . Suppose we want to find where and why this e
Guides -
OCaml Programming Guidelines
Width of the Page
Justification : This width makes it possible to read the code on all displays and to print it in a legible font on a standard sheet. The page is 80 columns wide.
Resources -
Command-line Arguments
Sys.argv
<!-- $MDX dir=examples --> Note that ocaml launched a subprocess that actually runs the program where argv is args.ml arg1 arg2 arg3 . You can also compile your program using ocamlopt -o ar
Tutorials