369 search results for "function"
-
Values and Functions
Scopes and Environments
<!-- With respect to the environment, there are no means to: - List its contents - Clear its contents - Remove a definition - Reset it to an earlier state --> Top-level expressions are also statemen
Introduction -
Values and Functions
Inner Shadowing
<!-- A name-value pair in a local expression *shadows* a binding with the same name in the global environment. In other words, the local binding temporarily hides the global one, making it inaccessib
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 -
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 -
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 -
Higher Order Functions
Mapping Custom Data Types
Note that the structure of the tree is preserved, but every time we encounter a value , we update it with (fn value) . When working with our custom data types, such as the tree we used in the
Introduction -
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 -
Basic Data Types and Pattern Matching
Introduction
ng dedicated syntax - Write variant type definitions: simple, recursive, and polymorphic - Write record type definitions (without mutable fields) - Write type aliases - Use pattern matching to define functions for all basic type --> Note : As in previous tutorials, expressions after # and ending with ;; are for the toplevel, like UTop. In OCaml, there are no type checks at runtime, and values don't
Introduction -
Basic Data Types and Pattern Matching
Results
Operations on results are provided by the Result module. Results are discussed in the Error Handling guide. The result type can be used to express that a function's outcome can be either success or failure. There are only two ways to build a result value: either using Ok or Error with the intended meaning. Both constructors can hold any kind of data. The
Introduction -
Basic Data Types and Pattern Matching
Function Parameter Aliases
This is useful for matching variant values of parameters. Function parameters can also be given a name with pattern matching for tuples and records.
Introduction -
Basic Data Types and Pattern Matching
Conclusion
) on OCaml. OCaml aggregates several type systems, also known as disciplines: - A [nominal type system](https://en.wikipedia.org/wiki/Nominal_type_system) is used for predefined types, variants, and functions. , and it is also the scope of this tutorial. - Two different [structural type systems](https://en.wikipedia.org/wiki/Structural_type_system) are also used: * One for polymorphic variants * Anot
Introduction -
Labelled and Optional Arguments
Passing Labelled Arguments
Note : Passing labelled arguments through the pipe operator ( |> ) throws a syntax error: Labelled arguments are passed using a tilde ~ and can be placed at any position and in any order. The function Option.value from the standard library has a parameter labelled default .
Introduction -
Labelled and Optional Arguments
Function with Only Optional Arguments
Without the unit parameter, the optional argument cannot be erased warning would be emitted. When all parameters of a function need to be optional, a dummy, positional and occurring last parameter must be added. The unit () value comes in handy for this. This is what is done here.
Introduction -
Labelled and Optional Arguments
Conclusion
Functions can have named or optional parameters. Refer to the reference manual for more examples and details on labels.
Introduction -
Mutability and Imperative Control Flow
References
The function ref : 'a -> 'a ref that creates a reference The type of mutable references: 'a ref The ref identifier above refers to two different things: The value { contents = 0 } is bound to the name d
Introduction -
Mutability and Imperative Control Flow
Assignment Operator
The update takes place as a side effect , and the value () is returned. the reference to be updated, and the value that replaces the previous contents. The assignment operator := is just a function. It takes
Introduction -
Mutability and Imperative Control Flow
Dereference Operator
them is possible. When working with mutable data in OCaml, Refer to the Operators documentation for more information on how unary and binary operators work in OCaml. The dereference operator is a function that takes a reference and returns its contents.
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 language, it has no type. In contrast to references, there is no special syntax to dereference a mutable recor
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), the counter decreases on every iteration of the loop. The body of
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: Memoization
und in the cache (it's a miss), and the result is computed, stored in the cache, and returned. However, instead of precomputing everything, memoization uses a cache that is populated when calling the function. Either, the provided arguments The memoization technique relies on the same idea as the previous section's example: lookup results from a table of previously computed values.
Introduction -
Modules
Interfaces and Implementations
module implementation) The public declarations of a module (the module interface) For this, we must distinguish: By default, anything defined in a module is accessible from other modules. Values, functions, types, or submodules, everything is public. This can be restricted to avoid exposing definitions that are not relevant from the outside.
Module System -
Modules
Stateful Modules
and third calls return the same results, showing that the internal state was reset. A module may have an internal state. This is the case for the Random module from the standard library. The functions Random.get_state and Random.set_state provide read and write access to the internal state, which is nameless and has an abstract type.
Module System -
Modules
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 other means to handle OCaml softwar
Module System -
Functors
Functors From the Standard Library
e 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 type t and associated functions. Refer to the documentation for the details about what they provide: Here is the module's signature that the functor Hashtbl.Make expects: Here is the module's signature that the functors S
Module System -
Functors
Dependencies Between Modules
-- dune exec funkt < dune . Module List through List.iter and f 's type Module Out_channel through Out_channel.output_string It embeds an additional IterPrint module that exposes a single function f of type string list -> unit and has two dependencies: funkt.ml Here is a new version of the funkt program:
Module System -
Functors
Replacing a Dependency
Note : Modules received and returned by IterPrint.Make both have a type t . The with type ... := ... constraint exposes that the two types t are the same. This makes functions from the injected dependency and result module use the exact same type. When the parameter's contained type is not exposed by the result module (i.e., when it is an implementation detail ), the wi
Module System -
Functors
Naming and Scoping
he same type as Dep.t ( List.t in this case). However, since Make is invoked to create module IterPrint in funkt.ml , the project fails to compile with the following error message: If the function f isn't used, the project compiles without error. Naively, we might have defined Iter.Make as follows: The with type constraint unifies types within a functor's parameter and result modules
Module System -
Functors
Write a Functor to Extend Modules
inside the toplevel, enter the following commands. scanLeft.ml dune dune-project Create a fresh directory with the following files: In this example, we extend List and Array modules with a function scan_left . It does almost the same as fold_left , except it returns all the intermediate values, not the last one as fold_left does. In this section, we define a functor to extend several modul
Module System -
Functors
Conclusion
Functor application essentially works the same way as function application: passing parameters and getting results. The difference is that we are passing modules instead of values. Beyond comfort, it enables a design approach where concerns are not only separate
Module System -
First-Class Modules
When to Use First-Class Modules
performance (first-class modules have small runtime overhead) Complex module relationships with multiple dependencies Use functors when you need to: Pass different module implementations to the same function Store modules in data structures (lists, hash tables) Choose implementations at runtime based on configuration Build plugin systems Use first-class modules when you need to:
Module System -
First-Class Modules
Key Points
Pack modules with (module M : ModuleType) Unpack with let module M = (val x : ModuleType) in ... Functions can directly pattern match: fun (module M : ModuleType) -> ... Use with type constraint
Module System -
Options
The Standard Library Option Module
Most of the functions in this section, as well as other useful ones, are provided by the OCaml standard library in the Stdlib.Option module.
Data Structures -
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
Length of an Array
The Array.length function returns the size of an array:
Data Structures -
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 that takes a key, a value, and the map to which it will be added. It returns a new map with that key-value pair added:
Data Structures -
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 key and a map. It returns a new map with that key's entry removed.
Data Structures -
Maps
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 Structures -
Maps
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 Structures -
Maps
Map a Map
sing string_of_int . Using StringMap.map , we create a map associating keys with string values: The lucky_numbers map associates string keys with integer values: Map modules have a map function:
Data Structures -
Sets
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 single element is created using Strin
Data Structures -
Sets
Working With Sets
Let's look at a few functions for working with sets using these two sets.
Data Structures -
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 immutable, so
Data Structures -
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 -
Sets
Union of Two Sets
With the function StringSet.union , we can compute the union of two sets.
Data Structures -
Sets
Intersection of Two Sets
With the function StringSet.inter , we can compute the intersection of two sets.
Data Structures -
Sets
Subtracting a Set from Another
With the function StringSet.diff , we can remove the elements of the second set from the first set.
Data Structures -
Sets
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 Structures -
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 -
Sets
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 information, refer to Set in the Standard Library documentation.
Data Structures