667 search results for ""
- 
                
                  Values and FunctionsScopes 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
- 
                
                  ObjectsImmediate Objects and Object Typesspeed : slightly faster field access in records field names : it is inconvenient to manipulate records of different types when some fields are named identically but it's not a problem with object Advanced Topics
- 
                
                  OCaml Programming GuidelinesClarity of OCaml CodeThe language features numerous programming styles (or programming paradigms): imperative programming (based on the notion of state and assignment), functional programming (based on the notion of Resources
- 
                
                  MemoizationMemoization Using Higher-order FunctionsNow we can slightly rewrite the original fib function above using this general memoization technique: For recursive functions, however, the recursive call structure needs to be modified. T Data Structures
- 
                
                  Understanding the Garbage CollectorThe Fast Minor HeapTo garbage-collect the minor heap, OCaml uses copying collection to move all live blocks in the minor heap to the major heap. This takes work proportional to the number of live blocks in the mi Runtime & Compiler
- 
                
                  Comparison of Standard ContainersSet and Map: Immutable TreesSets and maps are very useful in compilation and metaprogramming, but in other situations, hash tables are often more appropriate (see below). Adding an element: O(log n) Returning the number of Resources
- 
                
                  OCaml Programming GuidelinesIndentation of ProgramsSo each time, you must choose between the different styles suggested. The only absolute rule is the first below. When a justification for the adopted style has seemed obvious to me, I have ind Resources
- 
                
                  OCaml Programming GuidelinesHow to Edit ProgramsDevelopers describe how to use these features: the CTRL-C-CTRL-C combination recompiles the whole application; then, in case of errors, a succession of CTRL-X-` commands permits correction of Resources
- 
                
                  Memory Representation of ValuesCustom Heap BlocksThe custom operations specify how the runtime should perform polymorphic comparison, hashing and binary marshaling. They also optionally contain a finalizer that the runtime calls just before th Runtime & Compiler
- 
                
                  Configuring Your EditorUsing vim.lsp With runtimepathThen enable them in the toplevel init.lua . Add your LSP config to lsp/ocamllsp.lua . Your Neovim config should have the following structure now. Run the following at the root of your config Tooling
- 
                
                  Error HandlingUsing the option Type for ErrorsIt tends to be considered good practice nowadays when a function can fail in cases that are not bugs (i.e., not assert false , but network failures, keys not present, etc.) to return type such a Guides
- 
                
                  OCaml Programming GuidelinesGeneral principlesArrows of pattern-matching clauses should not be aligned. If an expression in a clause is too large to fit on one line, you must break the line immediately after the arrow of the corresponding cla Resources
- 
                
                  Introduction to the OCaml ToplevelLoading Libraries In UTopTip : UTop knows about the available libraries and completion works. Outside utop you can use ocamlfind list to display the complete list of libraries. Note that opam package may bundle several l Tooling
- 
                
                  Error HandlingTurning Exceptions into option or resultSome may like to turn this into a higher-order generic function: It would be same for result , except some data must be provided to the Error constructor. The standard library does not prov Guides
- 
                
                  Managing Dependencies With opamAdding Dependencies From a Git RepositorySometimes, you may want to install a package directly from a Git repository, e.g., when it is not available on the opam repository or when you want to use an unreleased version. Projects
- 
                
                  DebuggingPrinting a Back Trace for an Uncaught ExceptionThe environment variable OCAMLRUNPARAM also works when working on a program built with dune : From this back trace it should be clear that we receive a Not_found exception in List.assoc Guides
- 
                
                  Libraries With DuneRemove Duplicated InterfacesThis result is the same, except implementations Cumulus.M and Stratus.M are explicitly bound to the same interface, defined in module Wmo . wmo.ml wmo.mli Here is a possible way to fix th Module System
- 
                
                  OCaml Programming GuidelinesStyle dangersAnother common “over-imperative error” in the imperative world is not to systematically choose the simple for loop to iterate on a vector's element, but instead to use a complex while loo Resources
- 
                
                  A Tour of OCamlPattern Matching, Cont'dNote that OCaml throws a warning when pattern matching does not catch all cases: The underscore symbol is a catch-all pattern; it matches with anything. In this other example, the same comparis First Steps
- 
                
                  Values and FunctionsRecursive FunctionsNote : Notice that the fib_loop function has three parameters m n i but when defining fib only two arguments were passed 0 1 , using partial application. The second version fib uses the fir Introduction
- 
                
                  OCaml Programming GuidelinesPattern-matching in named functions<!-- $MDX skip --> Pattern-matching in functions defined by let or let rec gives rise to several reasonable styles that obey the preceding pattern-matching rules (the one for anonymous fun Resources
- 
                
                  OCaml Programming GuidelinesComparisons and Boolean operatorsComparisons are infix operators, so the preceding rules apply. This is why f x < g x means (f x) < (g x) . For type reasons (and no other sensible interpretation), the expression f x < x + 2 Resources
- 
                
                  Values and FunctionsPattern Matching in Definitions<!--the example illustrates tuples::--> When pattern matching only has one case, it can be used in name definitions and in let ... = and fun ... -> expressions. In that case, less or more than Introduction
- 
                
                  Managing Dependencies With opamInstalling a Dependency in Your Switchinstead. If you want to install a specific version of the package, use to get the latest version of the package. Installing a package from the opam repository to your active switch, you can run Projects
- 
                
                  OCaml Programming GuidelinesAvoid Nocuous Comments<!-- $MDX skip --> An example of what to avoid, the following comment uses technical words and is thus masquerading as a real comment, but it has no additional information of interest: Absolu Resources
- 
                
                  Configuring Your Editor3) OCaml Commands With Ctrl + Shift + PPressing the key combination Ctrl + Shift + P opens a modal dialog at the top. If you type the word ocaml , you will be presented with a list of various OCaml commands at your disposal which can b Tooling
- 
                
                  OCaml Programming GuidelinesHow to Write Long Character Strings<!-- $MDX skip --> Indent long character strings with the convention in force at that line, plus an indication of string continuation at the end of each line (a \ character at the end of the l Resources
- 
                
                  Understanding the Garbage CollectorNext-Fit AllocationNext-fit allocation is quite a cheap allocation mechanism, since the same heap chunk can be reused across allocation requests until it runs out. This in turn means that there is good memory loc Runtime & Compiler
- 
                
                  Comparison of Standard ContainersStrings: Immutable VectorsAdding an element (by creating a new string): O(n) Length: O(1) Accessing character i : O(1) Finding an element: O(n) Strings are very similar to arrays, but they are immutable. Strings are s Resources
- 
                
                  Memory Representation of ValuesString ValuesCare should be taken that any C library functions that receive these buffers can also cope with arbitrary bytes within the buffer contents and are not expecting C strings. For instance, the C me Runtime & Compiler
- 
                
                  SequencesSequence Consumers: Partially Applied Functions as ParametersA 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 Structures
- 
                
                  Higher Order FunctionsBinding as early returnsThe main difference is that in this case Result.bind is biased towards Ok value , so that if a result value is an Error reason , it will short-circuit through the binds and just return the first Introduction
- 
                
                  Common Error Messagesx.cmi is not a compiled interfaceIt means that some_module.cmi is not valid according to the current version of the OCaml compiler. Most of the time, removing the old compiled files ( .cmi, .cmo, *.cmx, ...) and recompiling is Resources
- 
                
                  ModulesInterfaces and ImplementationsThis triggers a compilation error. You can check that Cairo.message is not public by attempting to compile a delhi.ml file containing: Compile and execute both programs: Update the dune Module System
- 
                
                  Mutability and Imperative Control FlowImmutable vs Mutable DataIn the following sections, we introduce OCaml's language features for dealing with mutable states. When you use let … = … to bind a value to a name, this name-value binding is immutable , s Introduction
- 
                
                  Common Error MessagesWarning: Illegal backslash escape in stringRecent versions of OCaml warn you against unprotected backslashes in strings since they should be doubled. Such a message may be displayed when compiling an older program, and can be turned off Resources
- 
                
                  OCaml Programming GuidelinesBe Simple and ReadableWriting programs law : A program is written once, modified ten times, and read 100 times. So it's beneficial to simplify its writing, always keep future modifications in mind, and never jeopardi Resources
- 
                
                  Common Error MessagesThis pattern is unusedIn our example, it is now clear that only the first item of the pair will ever be tested. This leads to the following results: the tree of cases is traversed linearly, from left to right. There Resources
- 
                
                  The Compiler Frontend: Parsing and Type CheckingSyntax ErrorsThe syntax error points to the line and character number of the first token that couldn't be parsed. In the broken example, the module keyword isn't a valid token at that point in parsing, so t Runtime & Compiler
- 
                
                  Hash TablesCreating a Polymorphic Hash TableThe '_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 Structures
- 
                
                  Introduction to opam SwitchesSelecting a SwitchLearn more details and uses of opam switches in the opam manual's File Hierarchies page and its page dedicated to switches . Command-Line Flag : Use the --switch <switch> command-line flag to Tooling
- 
                
                  Comparison of Standard ContainersBuffer: Extensible StringsAdding a char: O(1) if the buffer is big enough, or O(log n) on average if the initial buffer size was much smaller than the number of bytes n . Adding a string of k chars: O(k * "adding Resources
- 
                
                  OCaml Programming GuidelinesOther Emacs tricksUnder Unix, the CTRL-C-CTRL-C or Meta-X compile combination, followed by CTRL-X-` , is also used to find all occurrences of a certain string in a OCaml program. Instead of launching mak Resources
- 
                
                  OCaml Programming GuidelinesSingle branchesIf cond , e1 , and e2 are small, simply write them on one line: If the expressions making up a conditional are purely functional (without side effects), we advocate binding them within the Resources
- 
                
                  OCaml Programming GuidelinesMultiple branchesYet again, choose your style and use it systematically. Justification : elsif is a keyword in many languages, so use indentation and else if to bring it to mind. Moreover, you do not have t Resources
- 
                
                  Mutability and Imperative Control FlowByte Sequences<!-- FIXME: link to a dedicated Byte Sequences tutorial --> Note : the bytes type uses a much more compact memory representation than char array . As of writing this tutorial, there is an 8-fact Introduction
- 
                
                  A Tour of OCamlRecursive FunctionsEach => sign corresponds to the computation of a recursive step, except the last one. OCaml handles lists internally, as shown in the penultimate expression, but displays them as the last expressio First Steps
- 
                
                  Error HandlingErrors as Special ValuesThe rest of this document presents and compares approaches towards error handling. Exceptions provide a means to deal with errors at the control flow level, while option and result make error Guides
- 
                
                  OCaml Programming GuidelinesPattern-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 function keyword: Resources
- 
                
                  Mutability and Imperative Control FlowGood: MemoizationYou can find a concrete example of memoization and an in-depth explanation in the chapter on Memoization of "OCaml Programming: Correct + Efficient + Beautiful." are found in the cache (it is a hi Introduction