816 search results for ""
-
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 -
Arrays
Copying Part of an Array into Another Array
This copies two elements of zeroes , starting at index 1 into the last part of zeroes , starting at index 3 . We can also use this function to copy part of an array onto itself: This copies
Data Structures -
Arrays
Conclusion
In this tutorial, we covered the basics of arrays in OCaml, including how to create and manipulate them, as well as some of the most useful functions and use cases. Please refer to the standard libr
Data Structures -
Maps
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 StructuresMaps
Creating a Map
Example 2 : By Adding an Element Example 1 : By Annotation When you create your new map with an annotation By adding an element to the map: The type of the values can be specified in two ways: T
Data StructuresMaps
Working With Maps
Throughout the rest of this tutorial, we will use the following map:
Data StructuresMaps
Finding Entries in a Map
Note that find_first_opt and find_last_opt return the key-value pair, not just the value. The functions find_first and find_last behave similarly, except they throw exceptions instead of
Data StructuresMaps
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 StructuresMaps
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 StructuresMaps
Changing the Value Associated With a Key
You should experiment with different update functions; several behaviors are possible. To change a key's associated value, use the update function. It takes a key, a map, and an update functio
Data StructuresMaps
Checking if a Key is Contained in a Map
To check if a key is a member of a map, use the mem function:
Data StructuresMaps
Merging Maps
pick_fst picks the result's value from the first map pick_snd picks the result's value from the second map drop drops both entries in the result map Here are examples of duplicate key resolut
Data StructuresMaps
Filtering a Map
To filter a map, use the filter function. It takes a predicate to filter entries and a map. It returns a new map containing the entries satisfying the predicate.
Data StructuresMaps
Map a Map
The keys are the same in both maps. For each key, a value in lucky_numbers is converted into a value in lucky_strings using string_of_int . Using StringMap.map , we create a map associatin
Data StructuresMaps
Maps With Custom Key Types
Note that our module has a type t and also a compare function. Now we can call the Map.Make functor to get a map for non-negative numbers: We'll start by defining a module for strings th
Data StructuresMaps
Conclusion
For more information, refer to Map in the Standard Library documentation. This was an overview of OCaml's Map module. Maps are reasonably efficient and can be an alternative to the imperativ
Data StructuresSets
Sets
Introduction
type elt = string for the elements, and type t = Set.Make(String).t for the sets. This module also defines two types: After naming the newly-created module StringSet , OCaml's toplevel displays t
Data StructuresSets
Creating a Set
There's another relevant function StringSet.of_seq: string Seq.t -> StringSet.t that creates a set from a sequence . Converting a list into a set using StringSet.of_list : A set with a sing
Data StructuresSets
Working With Sets
Let's look at a few functions for working with sets using these two sets.
Data StructuresSets
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 StructuresSets
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 StructuresSets
Union of Two Sets
With the function StringSet.union , we can compute the union of two sets.
Data StructuresSets
Intersection of Two Sets
With the function StringSet.inter , we can compute the intersection of two sets.
Data StructuresSets
Subtracting a Set from Another
With the function StringSet.diff , we can remove the elements of the second set from the first set.
Data StructuresSets
Filtering a Set
The function StringSet.filter of type (string -> bool) -> StringSet.t -> StringSet.t creates a new set by keeping the elements that satisfy a predicate from an existing set.
Data StructuresSets
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 StructuresSets
Sets With Custom Comparators
You can use any type for elements, as long as you define a meaningful compare operation. The value "HELLO" is not added to the set because it is considered equal to the value "hello" , which
Data StructuresSets
Conclusion
We gave an overview of OCaml's Set module by creating a StringSet module using the Set.Make functor. Further, we looked at how to create sets based on a custom comparison function. For more inf
Data StructuresHash Tables
Hash Tables
Introduction
A hash table data structure achieves efficient reads and writes by employing a hashing function that converts the key of a key/value pair into an algorithmically unique "fingerprint" known as a h
Data StructuresHash Tables
Creating a Polymorphic Hash Table
The '_weak1 and '_weak2 correspond to the key and value types, respectively. There are no concrete types (e.g., int or float * string ) filled in those slots because the type of the key an
Data StructuresHash Tables
Adding Data to a Hash Table
Where the type used to be the polymorphic (_weak1, _weak2) , it now has the concrete representation of (string * string) . Now that we put data into my_hash , let's look at its type: The ret
Data StructuresHash Tables
Finding Data in Hash Tables
This returns ["hard"; "hug"; "hi"; "hello"] , demonstrating that hashed key collisions are associated with a list of values associated with that key. However, the previous values associated wit
Data StructuresHash Tables
Removing Data from Hash Tables
This behavior is interesting for the above example or when, say, the keys represent variables that can be temporarily masked by a local variable of the same name. If you remove a key, its prev
Data StructuresHash Tables
Replacing Data in Hash Tables
To find out whether there is an entry in my_hash for a letter we would do: In other contexts, one may prefer new values replace the previous ones. In this case, one uses Hashtbl.replace
Data StructuresSequences
Sequences
Introduction
In OCaml, any value a of type t can be turned into a constant function by writing fun _ -> a or fun () -> a . The latter function is called a thunk . Using this terminology, Seq.t value
Data StructuresSequences
Constructing Sequences
The OCaml Standard Library contains a module for sequences called Seq . It contains Seq.int , which we implemented above. The function ints n looks as if building the infinite sequence (n; n +
Data StructuresSequences
Iterating Over Sequences
The key point is that it doesn't leak memory. This example runs in constant space. It is effectively nothing more than an infinite loop, which can be confirmed by monitoring the space consumption
Data StructuresSequences
Taking Parts of a Sequence
( Seq.ints i is the infinite sequence of the integers beginning at i and counting up.) This can be used to print integers without looping forever, as shown previously: When executed, the functio
Data StructuresSequences
Filtering a Sequence
Side Note : It may be interesting to learn that trial_div , while it can colloquially be called a recursive, is an example of a kind of recursion called corecursion . Corecursion differs from
Data StructuresSequences
Unfolding Sequences
The function Seq.uncons returns the head and tail of a sequence if it is not empty. Otherwise, it returns None . We can check our map function by applying a square function to a sequence:
Data StructuresSequences
Reading a File with Seq.Unfold
Note: production code should handle file opening errors, this example has been kept short to focus only on how files relate to sequences. Finally, let's read the file's contents using Seq.unfol
Data StructuresSequences
Consumers vs Producers
A function with a sequence parameter consumes it; it's a sequence consumer. A function with a sequence result produces it; it's a sequence producer. In both cases, consumption and production occurs o
Data StructuresSequences
Sequence Consumers: Partially Applied Functions as Parameters
A consumer is a function that processes a sequence, consuming its elements. Consumers should be written as higher-order functions that take a function parameter. This allows for deferred evalua
Data StructuresSequences
Consumer Example: Seq.iter
In print_seq , Seq.iter takes the function print_int and applies it to each element as they are generated. If List.iter was used, the whole integer list would be needed before displaying the
Data StructuresSequences
Sequence Producers: Functions as Results
A producer is a function that generates a sequence. Producers return a function so that elements are only computed when needed. This ensures deferred evaluation and avoids unnecessary computatio
Data StructuresSequences
Producer Example: Seq.unfold
This application of Seq.unfold has type unit -> int Seq.node , making it a function, a deferred producer. Each time this function is called, a new element is produced.
Data Structures