352 search results for "function"
-
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 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 -
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 pass in to sort : For lists, this [...] 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 -
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 b
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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 -
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
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 -
OCaml Programming Guidelines
Indentation to the function's name
evaluation order. As far as possible, avoid arguments which consist of complex expressions. In these cases, define the “large” argument by a let construction. No problem arises except for functions with many arguments—or very complicated arguments—which can't fit on the same line. You must indent the expressions with respect to the fucntion's name (1 or 2 spaces according to the chos
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 -
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 -
The Compiler Backend: Bytecode and Native code
Understanding Name Mangling
Anonymous functions are hard to predict without inspecting intermedi [...] odify the source code to let-bind the anonymous function to a variable name. The symbol is prefixed by caml and the local module name, with dots replac
Runtime & Compiler -
Memoization
Just for Fun: Party Optimization
We could memoize all calls, but that wouldn't improve speed much.) This requires just introducing a function `lb_mem` that looks up and records memoized forma [...] h the naive recursive implementation called the function party many times with the same arguments. Memoization saves all those calls. Further, the party o
Data Structures -
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 values are thunks. With the analogy used ear
Data Structures -
Sequences
Filtering a Sequence
s input incrementally. Unlike traditional recursion, which works towards a base case, corecursive functions must indefinitely produce values as a stream. The trial_div function is corecursive because it does not immediately compute the complete sequence of primes. Instead,
Data Structures -
Sequences
Unfolding Sequences
The function Seq.uncons returns the head and tail of a seque [...] ise, it returns None . We can check our map function by applying a square root
Data Structures -
Loops and Recursions
Mutable Records, References (Again!) and Arrays
OCaml won't let you: Anyway, let's see print_name in action: Notice a strange (and very non-functional) feature of print_name : it modifies its access_count parameter. This function is not "pure." OCaml is a
Introduction -
Lists
List Scanning
has evolved into its present state: pieces of frequently-used code are turned into useful general functions. This is rather clumsy, though. The standard library provides two useful functions for_all and exists for this common problem: There are more elaborate scanning
Introduction -
A Tour of OCaml
Defining a Higher-Order Function
It is possible to pass a function as argument to another function. Functions having other
First Steps -
A Tour of OCaml
Modules and the Standard Library
f the OCaml module system. It provides a means to separate concerns by preventing name clashes. Two functions having different type may have the same name if [...] provided by different modules. The List.map function which was used earlier in this section is also part of a module, the List module. When the optio
First Steps