652 search results for ""
-
Arrays
Accessing Array Elements
You can access individual elements of an array using the .(index) syntax, with the index of the element you want to access. The index of the first element is 0, and the index of the last element
Data Structures -
Basic Data Types and Pattern Matching
Options
Operations on options are provided by the Option module. Options are discussed in the Error Handling guide. Here is an example of pattern matching on an option value: The option type is a
Introduction -
Values and Functions
The Pipe Operator
This is just like a Unix shell pipe. The pipe operator ( |> ) also avoids parentheses but in reversed order: function on right, argument on left.
Introduction -
OCaml Programming Guidelines
Delimiters
A space should always follow a delimiter symbol, and spaces should surround operator symbols. It has been a great step forward in typography to separate words by spaces in order to make written t
Resources -
A Tour of OCaml
Anonymous Functions
We can write anonymous functions and immediately apply them to a value: Anonymous functions do not have a name, and they are defined with the fun keyword:
First Steps -
Basic Data Types and Pattern Matching
Type Aliases
This is mostly useful as a means of documentation or to shorten long type expressions. Just like values, any type can be given a name.
Introduction -
Installing OCaml
Join the Community
Make sure you join the OCaml community . You'll find many community members on Discuss or Discord . These are great places to ask for help if you have any issues.
First Steps -
Operators
Unary Operators
This allows users to write more compact code. However, be careful not to write excessively terse code, as it is harder to maintain. Understanding operators must be obvious to most readers, otherwise
Advanced Topics -
Lists
Association Lists
When using association lists, and for other purposes, it is sometimes useful to be able to make a list of pairs from a pair of lists and vice versa. The List module provides the functions sp
Introduction -
The Compiler Backend: Bytecode and Native code
Perf
<div class="note"> Perf has a growing collection of other commands that let you archive these runs and compare them against each other. You can read more on the home page . This trace broadly
Runtime & Compiler -
Arrays
Creating Arrays
Array.init generates an array of a given length by applying a function to each index of the array, starting at 0. The following line of code creates an array containing the first 5 even numbers us
Data Structures -
Your First OCaml Program
Watch Mode
Before we dive in, note that you will typically want to use Dune's watch mode to continually compile and optionally restart your program. This ensures that the language server has the freshest poss
First Steps -
Error Handling
Inherently Unsafe Functions
Some OCaml functions are inherently unsafe. Use them with care, not like this:
Guides -
Debugging
The OCaml Debugger
ocamldebug runs on ocamlc bytecode programs (it does not work on native code executables), and it does not work under native Windows ports of OCaml (but it runs under the Cygwin port). We now
Guides -
Higher Order Functions
Iterating
Iterating in OCaml means that if there is one value (or more), we'd like to apply a function to it. But in OCaml the pattern for iteration can be extended to other kinds of data types, like optional
Introduction -
The Compiler Backend: Bytecode and Native code
Gprof
Getting precise information out of gprof requires passing the -p flag to the native code compiler when compiling and linking the binary. This generates extra code that records profile infor
Runtime & Compiler -
Lists
Functions on Lists
Notice that the memory for the second list is shared, but the first list is effectively copied. Why is this? Because in the pattern _ :: t the head of the list is not inspected, so its type
Introduction -
Functors
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 System -
Lists
Maps and Iterators
Notice that map2 and iter2 will fail if the lists are of unequal length: There is a variant iter2 for two lists too: In addition, we have an imperative analogue to map , called
Introduction -
A Tour of OCaml
Records
Here, the pattern { age = x; _ } is typed with the most recently declared record type that has an age field of type int . The type int is inferred from the expression 13 <= x && x <= 19 . The
First Steps -
OCaml on Windows
Docker Images
The ocaml/opam Docker Hub repository now contains regularly-updated Windows images. This includes images using msvc and mingw . If you are comfortable with Docker, this might be an easier w
Resources -
Maps
Introduction
When we created the StringMap module, we fed the Map.Make functor the String module to define the type of the map's keys, which we can observe in the StringMap 's signature ( type key stri
Data Structures -
Modules
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 System -
Basic Data Types and Pattern Matching
Unit
The function print_endline prints the string followed by a line ending on standard output. Return of the unit value means the output request has been queued by the operating system. Note : Replace
Introduction -
Using the OCaml Playground
Autocomplete
Autocomplete in the OCaml Playground The playground also supports code completion. It helps users by suggesting and completing their input based on the context.
Resources -
Using the OCaml Playground
Bottom Line
Congratulations! You have made it to the end. Hopefully, by now, you have a better idea how to use the OCaml Playground . Use this to practice the OCaml code and have fun. Happy Hacking!
Resources -
Sets
Adding an Element to a Set
The function StringSet.add with type string -> StringSet.t -> StringSet.t takes both a string and a string set. It returns a new string set. Sets created with the Set.Make functor in OCaml are
Data Structures -
Modules
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 System -
Lists
List Searching
Note that the documentation for filter and partition tells us that the order of the input is preserved in the output. Where this is not stated it the documentation, it cannot be assumed.
Introduction -
Arrays
The Standard Library Array Module
OCaml provides several useful functions for working with arrays. Here are some of the most common ones:
Data Structures -
Arrays
Iterate on an Array
Iterating on arrays can also be made using for loops. Here is the same example using a loop: Array.iter applies a function to each element of an array, one at a time. The given function must
Data Structures -
Using the OCaml Playground
Caveat
In contrast, when you separate these expressions with a ;; , like this , or when you bind them to names, like this , they are evaluated successfully, one after another. A little caveat here is
Resources -
Error Handling
Stack Traces
And you will get a stack trace. Alternatively, you can call, from within the program, To get a stack trace when an unhandled exception makes your program crash, you need to compile the progr
Guides -
Maps
Removing Entries From a Map
Note that the initial map lucky_numbers remains unchanged. Removing a key that isn't present in the map has no effect. To remove an entry from a map, use the remove function, which takes a ke
Data Structures -
Arrays
Introduction
Storing and processing large amounts of data Implementing algorithms that require random access and modification of elements Working with matrices and other multi-dimensional data structures Arrays
Data Structures -
Higher Order Functions
Let-ops
This has the advantage of making code a lot more readable, without changing the behavior we've come to expect from bind calls. Thankfully, OCaml lets us redefine a subset of operators called let-
Introduction -
Options
Introduction
The option type is useful when the lack of data is better handled as the special value None rather than an exception. It is the type-safe version of returning error values. Since data wrapped in an
Data Structures -
Higher Order Functions
Binding
To do this with lists we can use the concat_map function, which looks like this: For example, if we have a list and we map over it with a function that returns a list, then we'll have a list of
Introduction -
Higher Order Functions
Sorting
Most OCaml modules include a compare function that can be pass in to sort : For lists, this operation returns a new sorted list: For arrays, this operation mutates the array in-place: Bot
Introduction -
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 System -
Arrays
Sorting an Array
It sorts the provided array in place and in ascending order, according to the provided comparison function. Sorting performed by Array.sort modifies the content of the provided array, which is wh
Data Structures -
A Tour of OCaml
Exceptions
The standard library provides several predefined exceptions. It is possible to define exceptions. Exceptions are caught using the try … with … construction: Note that exceptions do not appe
First Steps -
Loops and Recursions
Approach 1
Get the length of the file and read it all at once using the really_input method. This is the simplest, but it might not work on channels that are not really files (e.g., reading keyboard input)
Introduction -
Maps
Adding Entries to a Map
Note that the initial map lucky_numbers remains unchanged. If the passed key is already associated with a value, the passed value replaces it. To add an entry to a map, use the add function t
Data Structures -
OCaml Programming Guidelines
How to Program
Always put your handiwork back on the bench, then polish it and repolish it.
Resources -
OCaml Programming Guidelines
Credits
Thanks to all those who have already participated in the critique of this page: Daniel de Rauglaudre, Luc Maranget, Jacques Garrigue, Damien Doligez, Xavier Leroy, Bruno Verlyck, Bruno Petazzoni,
Resources -
Sets
Checking if an Element is Contained in a Set
To check if an element is contained in a set, use the StringSet.mem function.
Data Structures -
Error Handling
Printing
Each printer should take care of the exceptions it knows about, returning Some <printed exception> , and return None otherwise (let the other printers do the job). OCaml knows how to print it
Guides -
Sets
Removing an Element from a Set
The function StringSet.remove with type string -> StringSet.t -> StringSet.t takes both a string and a string set. It returns a new string set without the given string.
Data Structures -
Lists
List Scanning
So you can see how the standard library has evolved into its present state: pieces of frequently-used code are turned into useful general functions. This is rather clumsy, though. The standard l
Introduction