379 search results for "function"
-
OCaml Programming Guidelines
Naming Anonymous Functions
Justification : Much clearer, in particular if the name given to the function is meaningful. <!-- $MDX skip --> write <!- [...] e case of an iterator whose argument is a complex function, define the
Resources -
OCaml Programming Guidelines
Pattern-matching in anonymous functions
<!-- $MDX skip --> Similarly to match or try , pattern-matching of anonymous functions, starting with function , are indented with respect to the
Resources -
A Tour of OCaml
Polymorphic Functions on Lists
This function operates not just on lists of integers but on any kind of list. It is a polymorphic function. Its type indicates input of type 'a list where 'a is a type variable standing for any type. Th
First Steps -
Lists
Folds
Here are some more redefinitions of familiar functions in terms of fold_left or fold_right . Can y [...] he @ operator as its first argument, and so the function has a worse running time than List.concat . You can read more about the time and space effici
Introduction -
Higher Order Functions
Iterating over Lazy Sequences
This is almost exactly how Seq.iter is defined in the standard library. This function will try to get the first element of the sequence, and if there is one, run our function fn over it. Then it will repeat over the new sequence ( seq2 ) which starts at the second element
Introduction -
Error Handling
Using Fun.protect
ng an exception. Either way, the file descriptor is closed after use. Let's demonstrate with a function that tries reading the first n lines of a tex [...] ad ). If the file has fewer than n lines, the function must throw End_of_file . In any case, the file descriptor must be closed afterwards. Here is a p
Guides -
Profiling
Polymorphic Types
Lesson: if you have a function which is unintentionally polymorphic then you c [...] the module), OCaml still doesn't specialise the function. Here's another variation: Is OCaml going to be smart enough to inline the max
Guides -
First-Class Modules
Passing Modules to Functions
automatically unpacks the first-class module, making P available as a regular module inside the function. You can write functions that accept modules as parameters:
Module System -
Sequences
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 unne
Data Structures -
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 -
OCaml Programming Guidelines
The hd and tl Functions
which must be protected by try... with... to catch the exception that might be raised by these functions. Don't use the hd and tl functions, but rather pattern-match the list argument explicitly.
Resources -
OCaml Programming Guidelines
Pattern-matching in named functions
<!-- $MDX skip --> Pattern-matching in functions defined by let or let rec gives rise to se [...] g pattern-matching rules (the one for anonymous functions being evidently excepted). See above for recommended styles.
Resources -
OCaml Programming Guidelines
Indentation to the function's name
hese cases, define the “large” argument by a let construction. No problem arises except for functions with many arguments—or very complicated argu [...] must indent the expressions with respect to the function's name (1 or 2 spaces according to the chosen convention). Write small arguments on the same li
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 -
Values and Functions
Partial Application and Closures
ressions have the same value: Passing a single argument to sour_kitty or sweet_kitty returns a function of type string -> string . The first argument, [...] esult is a closure . Since a multiple-parameter function is a series of nested single-argument
Introduction -
Higher Order Functions
Iterating over Lists
how List.iter is defined in the standard library. And this way we can call print_all with any function fn , so it really is just iterating over the list and running a function over every element. Now if we wanted to do something else with each element of the list, we coul
Introduction -
Higher Order Functions
Iterating over Maps and Sets
The actual implementation of iteration functions for Maps and Sets does use pattern-matching unde [...] Sets and Maps is private. With either of those functions, we can put together an iterator over maps or sets: Once you create your Set or Map module, you'l
Introduction -
Functors
Using an Existing Functor: Set.Make
, the string "funkt" is only displayed once, although it appears twice in the dune file. The functions StringSet.of_list and StringSet.iter are ava [...] provides the operations on sets of strings. The function String.compare is used internally by StringSet . This can be simplified even further into thi
Module System -
Operators
Using Binary Operators
ted by List.filter are provided. The returned list contains the values satisfying the ( <= ) 10 function. The first shows the List.filter type, which is a function taking two parameters. The first parameter is a
Advanced Topics -
Operators
Binding Operators
TODO: move this into the list tutorial In the following example, we use that mechanism to write a function which produces the list of Friday 13th dates betw [...] egers between `lo` and `hi`, including both. The function `day_of_week` calculates the day of the week for a given date. Generative large language model chat
Advanced Topics -
Calling Fortran Libraries
Step 2: Create the C Wrapper
The file must include the OCaml header files alloc.h , memory.h , and mlvalue.h . The function first calls the CAMLparam5 macro. This is required at the start of any function that uses the CAML types. The
Tutorials -
Error Handling
Using the result Type for Errors
e code that behaves incorrectly or fails under exceptional conditions. The right tools, data, and functions can help you ensure correct behavior with mini [...] haviour can be achieved by defining the following function: Result.map_error f (Ok x) = Ok x And either: Result.map_error f (Error e) = Ok y Result.map_error
Guides -
Error Handling
Using on Option.map and Option.bind
a return value. None is silent, it doesn't say anything about what went wrong. For this reason, functions returning option values should document the ci [...] tern often found in C. As in the original host function (with exceptions): The calls to String
Guides -
Values and Functions
Pattern Matching in Function Parameters
Note Using the discard pattern for parameter declaration is also possible. Here is an example with the name record: Here is an example with tuples: Single-case pattern matching can also be
Introduction -
Values and Functions
Functions with Multiple Parameters
Introduction -
Higher Order Functions
Readability Notes
currying that would most likely be easier to read and maintain if we manually wrote out the wrapper functions: Sometimes it makes sense to curry a function, and sometimes the clearer thing is to manually wrap it in a
Introduction -
Higher Order Functions
Folding (or reducing)
And voila! Our function now type-checks correctly and we can use it to re [...] ty". But we quickly run into a problem: our fn function is meant to combine two items, so in the Leaf branch, what is the second item? And if we gener
Introduction -
Higher Order Functions
Sorting
Most OCaml modules include a compare function that can be passed in to sort : For lists, th [...] rt implement an interface where if you pass in a function that knows how to compare 2 elements, they'll adapt the sorting to use this comparison. Another co
Introduction -
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 lists. Sometimes we want this, but sometimes we woul
Introduction -
Loops and Recursions
Looping Over Lists
(Notice that this factorial function isn't very useful because it overflows the inte [...] mething more interesting, I first need a range function that builds the list of integers between two bounds. I'll come back to how it works in the Recur
Introduction -
Labelled and Optional Arguments
Optional Arguments and Partial Application
Note : Optional parameters make it difficult for the compiler to know if a function is partially applied or not. This is why at least [...] nal ones. If present at application, it means the function is fully applied, if missing, it means the
Introduction -
Options
Fold an Option
This function safely handles optional names by providing a fall [...] the option contains Some 5 , fold applies the function fun x -> x * 2 , resulting in 10 . Example 1 : Applying a
Data Structures -
Options
Bind an Option
value and ensures it falls within a valid range. Example 3 : Chaining Computations Notice how the function user_to_email does not require explicit pattern [...] _user . With Option.bind , we can let the bind function handle the unwrapping for us. Here, bind is used to wrap a value returned by a
Data Structures -
Understanding the Garbage Collector
What Values Can Be Finalized?
on determines that a heap block b is unreachable, it removes from the set of finalizers all the functions associated with b , and serially applies each of those functions to b . Thus, every finalizer
Runtime & Compiler -
How to Work with the Garbage Collector
Finalisation and the Weak Module
download the complete program and test code objcache.ml and compile it with: The sync_records function is even easier. First of all, it empties the ca [...] xamples/objcache.ml,part=4 --> The get_record function is very short and basically composed of two halves. We grab the record from the cache. If the cac
Guides -
OCaml Programming Guidelines
Function application: same rules as for trigonometric functions
In mathematics you write sin x to mean sin (x) . In the same way sin x + cos x means (sin x) + (cos x) not sin (x + (cos x)) . Use the same conventions in OCaml: write f x + g x to mean
Resources -
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 -
Loops and Recursions
Recursion
(into a long string). There are essentially three possible approaches to this: Writing recursive functions requires a change in mindset from writing for [...] xamples. Now we come to a hard topic: recursion. Functional programmers are defined by their love of recursive
Introduction -
Lists
Sorting Lists
The function Fun.flip reverses a binary function parameter order. The
Introduction -
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
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 -
Mutability and Imperative Control Flow
Good: Application-Wide State
the state is copied, which is not memory efficient. In a memory-aware implementation, state-update functions would produce a “diff” (data describing the [...] y to handle an application-wide state. As in the Function-Encapsulated Mutability example, state-aware code is contained in a narrow scope; the rest of the
Introduction -
Mutability and Imperative Control Flow
Bad: Undocumented Mutation
anti-pattern. “Mutable in disguise” is an unintended or undocumented side-effect performed by a function. “Stateful Influence” is the unintended or un [...] nfluence of some mutable state on the result of a function (as an external factor). --> In the latter case, the
Introduction -
Arrays
Folding an Array
These functions derive a single value from the whole array. For [...] ) Similarly, we can use the Array.fold_right function, which switches the order of its parameters: fold_left f init a computes f (... (f(f init a.(0))
Data Structures -
Objects
Inheritance, Virtual Classes, Initialisers
efore defining our label class, let's play with the button class in the OCaml toplevel: This function has an optional argument ( see the previous chapt [...] which is used to pass in the optional callback function. The callback is called when the button is pressed. The expression inherit container name as sup
Advanced Topics -
The Compiler Backend: Bytecode and Native code
The Impact of Polymorphic Comparison
the location of the minor heap in the %r15 register since it's so frequently referenced in OCaml functions. The minor heap pointer can also be changed by [...] hed on the stack (the %rsp register), and a C function call is invoked by placing a pointer to caml_greaterthan in %rax and jumping to caml_c_call
Runtime & Compiler -
Error Handling
Inherently Unsafe Functions
Some OCaml functions are inherently unsafe. Use them with care, not like this:
Guides -
Profiling
The “hello, world” Program
is if you pass an OCaml string to some C native code: if it contains ASCII NUL, then the C str* functions will fail on it. Firstly the padding brings t [...] l see about that later. OCaml has inlined this function. Inlining - taking a
Guides -
OCaml Programming Guidelines
Subdivide Your Programs Into Little Functions
Small functions are easier to master.
Resources -
OCaml Programming Guidelines
Sequence warnings and let _ = ...
ls to add accordingly. <!-- $MDX skip --> In actual programs, the suitable (side-effect-only) function may not exist and must be written. Frequently, [...] eful separation of the procedural part from the functional part of the
Resources