369 search results for "function"
-
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 Function to Some , Using a Default f
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 -
A Tour of OCaml
Functions
Some functions, such as String.ends_with have labelled parameters. Labels are useful when a function has several parameters of the same type; naming arguments allows to guess their purpose. Above, ~s
First Steps -
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 -
OCaml Programming Guidelines
No beastly indentation of functions and case analyses
aesthetic value is doubtful. <!-- $MDX skip --> but choose to indent the line under the let keyword: <!-- $MDX skip --> This consists in indenting normally under the keyword match or function that has previously been pushed to the right. Don't write:
Resources -
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 -
Error Handling
Inherently Unsafe Functions
Some OCaml functions are inherently unsafe. Use them with care, not like this:
Guides -
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 [...] in a narrow scope; the rest of the code is purely functional. 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 -
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 -
Loops and Recursions
Looping Over Lists
(Notice that this factorial function isn't very useful because it overflows the inte [...] se List.fold_left to define sum and product functions for integer lists: The fold operation does this, although the exact details are a little bit
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 [...] grammers are defined by their love of recursive functions, and in many ways recursive
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 -
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 -
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 -
A Tour of OCaml
Side-Effects and the unit Type
Input-output is an example of something taking place when executing a function but which does not appear in the function type. This is called a side-effect and does not stop at I/O. The unit type is often used to ind
First Steps -
Your First OCaml Program
Why Isn't There a Main Function?
ll those will take place in the same order. That's OCaml main. Although bin/main.ml 's name suggests it contains the application entry point into the project, it does not contain a dedicated main function, and there is no requirement that a project must contain a file with that name in order to produce an executable. A compiled OCaml file behaves as though that file were entered line by line into the
First Steps -
OCaml Programming Guidelines
Style dangers
ls that the mutable keyword in the record-type definitions should be implicit. The “too much functional” danger : The programmer that adheres to this [...] systematic rewriting for loops with recursive functions, using lists in contexts where imperative data structures seem to be mandatory to anyone, pass
Resources -
OCaml Programming Guidelines
OCaml code generally considered unreadable
atically code sequences with let in bindings. Mix computations and side effects, particularly in function calls. Recall that the evaluation order of function call arguments is unspecified, which implies that you must not mix side effects and computation
Resources -
Profiling
Tail Recursion
then print the string, and jump back, and so on forever. It's a simple loop, not a recursive function call, so it doesn't use any stack space. Here is the assembler for just the loop function defined above: The file is called tail.ml , so following OCaml's usual procedure for naming
Guides -
Profiling
The Representation of Integers, Tag Bits, Heap-Allocated Values
le_tag: Compare two floats. etc. It uses the following decision tree: Remember our polymorphic > function which caused us so much trouble in the previous [...] and found out that OCaml compiles a call to a C function called greaterthan whenever it sees the polymorphic form of >. This
Guides -
Formatting and Wrapping Text
Most General Pretty-Printing: Using fprintf
ng fprintf , the lambda-terms printing routines can be written as follows: We use the fprintf function to write the most versatile version of the pretty-printing functions for lambda-terms. Now, the
Tutorials -
Modules
Abstract and Read-Only Types
le to access a read-only record field's value, but creating such a record requires using a provided function. The type dalet is read-only . Pattern matchi [...] ut values can only be constructed by the provided functions, here dalet_of . Type gimel is abstract . Values can be created or manipulated, but only as
Module System