### Install Dependencies with Development Setup Source: https://melange.re/v5.0.0/package-management Installs project dependencies, including those marked for development setup. This flag ensures that development-specific dependencies are also installed. ```bash opam install --deps-only --with-dev-setup ``` -------------------------------- ### Install OCaml Syntax Formatting: Command Line Source: https://melange.re/v5.0.0/syntaxes Installs dependencies for OCaml syntax formatting, including dev setup, by running `opam install` with specific flags. This command prepares the environment for formatted OCaml code. ```bash opam install -y . --deps-only --with-dev-setup ``` -------------------------------- ### Install Project Dependencies Source: https://melange.re/v5.0.0/package-management Installs the project's dependencies based on the `app.opam` file. This command should be used when a local switch already exists. ```bash opam install . --deps-only ``` -------------------------------- ### Install and run the check-npm-deps opam plugin Source: https://melange.re/v5.0.0/package-management These commands demonstrate how to install the 'opam-check-npm-deps' plugin and then execute it from the project's root directory to verify that opam package constraints match installed npm packages. ```bash opam install opam-check-npm-deps ``` ```bash opam-check-npm-deps ``` -------------------------------- ### Install and Use rescript-syntax for Syntax Migration Source: https://melange.re/v5.0.0/how-to-guides This shows how to install the rescript-syntax package using opam and then use its command-line interface to convert ReScript (.res) files to OCaml (.ml) syntax. It also includes an example of converting multiple files using 'find'. ```bash opam install rescript-syntax ``` ```bash rescript_syntax myFile.res -print ml > myFile.ml ``` ```bash find src1 src2 -type f -name "*.res" -exec echo "rescript_syntax {} -print ml" \; ``` -------------------------------- ### Install Reason Syntax Support: Command Line Source: https://melange.re/v5.0.0/syntaxes Installs dependencies for Reason syntax support by running `opam install` with the `--deps-only` flag. This command ensures all required packages are fetched and installed. ```bash opam install -y . --deps-only ``` -------------------------------- ### Add opam package dependency to Dune build file Source: https://melange.re/v5.0.0/package-management This example illustrates how to include an installed opam package, such as 'reason-react', in the 'libraries' field of a Dune build file for a Melange project. It also shows how to specify preprocessors like 'reason-react-ppx'. ```dune (melange.emit (target output) (alias react) (libraries lib reason-react) (preprocess (pps reason-react-ppx)) (module_systems es6)) ``` -------------------------------- ### Hashtbl Key Comparison Examples Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/MoreLabels/Hashtbl/module-type-HashedType/index Illustrates common and recommended pairs of equality predicates and hashing functions for OCaml hashtable keys. These examples cover structural equality (with and without NaN handling) and physical equality. ```ocaml (* Example 1: Structural equality for immutable objects without floats *) val equal : 'a -> 'a -> bool val hash : 'a -> int (* Example 2: Structural equality handling Stdlib.nan correctly *) val equal : 'a -> 'a -> bool val hash : 'a -> int (* Example 3: Physical equality for mutable or cyclic objects *) val equal : 'a -> 'a -> bool val hash : 'a -> int ``` -------------------------------- ### startsWith Source: https://melange.re/v5.0.0/api/ml/melange/Js/String/index Checks if a string starts with a specified prefix, optionally at a given starting position. ```APIDOC ## startsWith ### Description Returns `true` if the string `str` starts with `prefix` starting at position `start`, `false` otherwise. If `start` is negative, the search starts at the beginning of `str`. ### Method N/A (Function definition) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ``` startsWith ~prefix:"Hello" ~start:0 "Hello, World!" = true;; startsWith ~prefix:"World" ~start:7 "Hello, World!" = true;; startsWith ~prefix:"World" ~start:8 "Hello, World!" = false;; ``` ### Response #### Success Response (200) N/A (Function return value) #### Response Example N/A ``` -------------------------------- ### Install Dune and Melange Source: https://melange.re/v5.0.0/build-system Updates the opam package repository and installs the latest versions of Dune and Melange. These are essential tools for building Melange applications. ```bash opam update opam install dune melange ``` -------------------------------- ### Example of fprintf Usage Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Format/index This example demonstrates the usage of `fprintf` with pretty-printing annotations. It formats a string and an integer, applying specific formatting rules within a pretty-printing box and ending with a newline. ```ocaml printf "@[%s@ %d@]@." "x =" 1 ``` -------------------------------- ### Install Reason Package Source: https://melange.re/v5.0.0/build-system Installs the 'reason' package, which is necessary if the project uses Reason syntax. This allows Melange to process ReasonML code. ```bash opam install reason ``` -------------------------------- ### Basic Example: Creating and Using a Hashtbl Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Hashtbl/index Demonstrates how to create a hash table from a sequence, add elements, and check its contents. ```APIDOC ### Basic Example ```ocaml (* 0...99 *) let seq = Seq.ints 0 |> Seq.take 100 (* build from Seq.t *) # let tbl = seq |> Seq.map (fun x -> x, string_of_int x) |> Hashtbl.of_seq val tbl : (int, string) Hashtbl.t = # Hashtbl.length tbl - : int = 100 # Hashtbl.find_opt tbl 32 - : string option = Some "32" # Hashtbl.find_opt tbl 166 - : string option = None # Hashtbl.replace tbl 166 "one six six" - : unit = () # Hashtbl.find_opt tbl 166 - : string option = Some "one six six" # Hashtbl.length tbl - : int = 101 ``` ``` -------------------------------- ### Nix Flake for Melange Development Environment Source: https://melange.re/v5.0.0/getting-started This Nix flake configuration sets up a development environment for Melange projects. It includes Melange, OCaml, Dune, and other essential OCaml development tools. Ensure Nix is installed before using this configuration. ```nix { description = "Melange starter"; inputs = { flake-utils.url = "github:numtide/flake-utils"; nixpkgs.url = "github:nixos/nixpkgs"; # Depend on the Melange flake, which provides the overlay melange.url = "github:melange-re/melange"; }; outputs = { self, nixpkgs, flake-utils, melange }: flake-utils.lib.eachDefaultSystem (system: let pkgs = nixpkgs.legacyPackages.${system}.appendOverlays [ # Set the OCaml set of packages to the 5.1 release line (self: super: { ocamlPackages = super.ocaml-ng.ocamlPackages_5_1; }) # Apply the Melange overlay melange.overlays.default ]; inherit (pkgs) ocamlPackages; in { devShells.default = pkgs.mkShell { nativeBuildInputs = with ocamlPackages; [ ocaml dune_3 findlib ocaml-lsp ocamlPackages.melange ]; buildInputs = [ ocamlPackages.melange ]; }; }); } ``` -------------------------------- ### Esy Configuration for Melange Project Source: https://melange.re/v5.0.0/getting-started This `esy.json` file defines the dependencies and build process for a Melange project using the esy package manager. It specifies OCaml, Dune, Melange, and the OCaml LSP server. Ensure esy is installed globally before using this configuration. ```json { "name": "melange-project", "dependencies": { "ocaml": "5.1.x", "@opam/dune": ">= 3.8.0", "@opam/melange": "*" }, "devDependencies": { "@opam/ocaml-lsp-server": "*" }, "esy": { "build": [ "dune build @melange" ] } } ``` -------------------------------- ### Basic Hashtbl Example Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Hashtbl/index Demonstrates the basic usage of the Hashtbl module, including creating a table from a sequence, adding elements, and retrieving them. ```APIDOC ## Basic Example ### Creating and Populating a Hashtbl from a Sequence ```ocaml (* Create a sequence of integers from 0 to 99 *) let seq = Seq.ints 0 |> Seq.take 100 (* Build a hashtable from the sequence, mapping integers to their string representations *) let tbl = seq |> Seq.map (fun x -> x, string_of_int x) |> Hashtbl.of_seq (* Check the length of the hashtable *) # Hashtbl.length tbl - : int = 100 (* Find an existing key *) # Hashtbl.find_opt tbl 32 - : string option = Some "32" (* Try to find a non-existent key *) # Hashtbl.find_opt tbl 166 - : string option = None (* Replace the value for an existing key, or add if it doesn't exist *) # Hashtbl.replace tbl 166 "one six six" - : unit = () (* Find the key again after replacement *) # Hashtbl.find_opt tbl 166 - : string option = Some "one six six" (* Check the length again, which increases if a new key was added *) # Hashtbl.length tbl - : int = 101 ``` ``` -------------------------------- ### Initialize Opam Environment Source: https://melange.re/v5.0.0/package-management Initializes the Opam environment, setting up the Opam root directory and fetching software repositories. This is a necessary first step for using Opam. ```bash opam init -a ``` -------------------------------- ### Update OCaml Switch and Install Melange v2 Source: https://melange.re/v5.0.0/how-to-guides This series of bash commands guides the user through updating their local opam repository, installing OCaml 5.3.0, and then upgrading all packages to ensure Melange v2 and compatible libraries are installed. ```bash opam update ``` ```bash opam install --update-invariant ocaml-base-compiler.5.3.0 ``` ```bash opam upgrade ``` -------------------------------- ### Basic Hashtable Creation and Manipulation (OCaml) Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Hashtbl/index A fundamental example of using OCaml's `Hashtbl` module. It shows how to create a hash table from a sequence of key-value pairs, check its length, find elements, and replace existing values. ```ocaml (* 0...99 *) let seq = Seq.ints 0 |> Seq.take 100 (* build from Seq.t *) # let tbl = seq |> Seq.map (fun x -> x, string_of_int x) |> Hashtbl.of_seq val tbl : (int, string) Hashtbl.t = # Hashtbl.length tbl - : int = 100 # Hashtbl.find_opt tbl 32 - : string option = Some "32" # Hashtbl.find_opt tbl 166 - : string option = None # Hashtbl.replace tbl 166 "one six six" - : unit = () # Hashtbl.find_opt tbl 166 - : string option = Some "one six six" # Hashtbl.length tbl - : int = 101 ``` -------------------------------- ### Get UTF-8 character at index - OCaml Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/String Decodes a UTF-8 encoded character starting at a given index within a string. Returns a `Uchar.utf_decode` result. ```ocaml val get_utf_8_uchar : t -> int -> Uchar.utf_decode get_utf_8_uchar b i decodes an UTF-8 character at index `i` in `b`. ``` -------------------------------- ### Get UTF-16LE character at index - OCaml Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/String Decodes a UTF-16 Little-Endian encoded character starting at a given index within a string. Returns a `Uchar.utf_decode` result. ```ocaml val get_utf_16le_uchar : t -> int -> Uchar.utf_decode get_utf_16le_uchar b i decodes an UTF-16LE character at index `i` in `b`. ``` -------------------------------- ### Basic Example Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/MoreLabels/Hashtbl/index Demonstrates the basic usage of Hashtbl functions like `of_seq`, `length`, `find_opt`, and `replace`. ```APIDOC ## Examples ### Basic Example ```ocaml (* 0...99 *) let seq = Seq.ints 0 |> Seq.take 100 (* build from Seq.t *) let tbl = seq |> Seq.map (fun x -> x, string_of_int x) |> Hashtbl.of_seq Hashtbl.length tbl (* Expected: 100 *) Hashtbl.find_opt tbl 32 (* Expected: Some "32" *) Hashtbl.find_opt tbl 166 (* Expected: None *) Hashtbl.replace tbl 166 "one six six" Hashtbl.find_opt tbl 166 (* Expected: Some "one six six" *) Hashtbl.length tbl (* Expected: 101 *) ``` ``` -------------------------------- ### Get UTF-16BE character at index - OCaml Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/String Decodes a UTF-16 Big-Endian encoded character starting at a given index within a string. Returns a `Uchar.utf_decode` result. ```ocaml val get_utf_16be_uchar : t -> int -> Uchar.utf_decode get_utf_16be_uchar b i decodes an UTF-16BE character at index `i` in `b`. ``` -------------------------------- ### Write String to Binary File (OCaml) Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Out_channel/index Example demonstrating how to open a file in binary mode and write a string to it using OCaml's Out_channel module. It ensures the file is properly closed after writing. ```ocaml let write_file file s = Out_channel.with_open_bin file (fun oc -> Out_channel.output_string oc s)) ``` -------------------------------- ### Get Set Size (OCaml) Source: https://melange.re/v5.0.0/api/ml/melange/Belt/Set/index Returns the number of unique elements in the set. Example shows a set created from an array and its size. ```OCaml let s0 = fromArray ~id:(module IntCmp) [|5;2;3;5;6|]];; size s0 = 4;; ``` -------------------------------- ### Basic Queue Operations Example Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Queue/index Demonstrates the fundamental usage of a queue, including creation, adding elements, checking length, and removing elements until the queue is empty. Shows the `Empty` exception when attempting to pop from an empty queue. ```ocaml let q = Queue.create () Queue.push 1 q; Queue.push 2 q; Queue.push 3 q Queue.length q Queue.pop q Queue.pop q Queue.pop q Queue.pop q ``` -------------------------------- ### Pretty-printing Box Management Example Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Format/index Demonstrates basic pretty-printing by opening a box, printing content, and closing the box. This sequence prints 'x = 1' with proper indentation and line breaks. ```ocaml open_box 0; print_string "x ="; print_space (); print_int 1; close_box (); print_newline () ``` -------------------------------- ### Get Start Position of Lexeme (OCaml) Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Lexing/index Similar to lexeme_start, but returns a complete position object instead of an offset. If position tracking is disabled, it returns a dummy position. ```OCaml let lexeme_start_p: lexbuf => position; Lexing.lexeme_start_p lexbuf ``` -------------------------------- ### Copying Data with Stdlib.Buffer.blit Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Buffer/index This example illustrates how to copy data from a buffer to an external byte sequence using `Buffer.blit`. It takes the source buffer, the starting offset in the source, the destination byte sequence, the starting offset in the destination, and the number of characters to copy. This function is useful for transferring parts of a buffer's content to another memory region. ```ocaml (* Assuming 'src_buffer' is a Buffer.t and 'dst_bytes' is a bytes *) let src_buffer = Buffer.create 100 let () = Buffer.add_string src_buffer "Hello, world!" let dst_bytes = Bytes.create 50 let () = Buffer.blit src_buffer 0 dst_bytes 0 5 (* Copy first 5 characters *) ``` -------------------------------- ### Example: Creating and Populating a Map with Custom Key Type Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Map/index This example demonstrates how to create a custom module `PairsMap` using the `Map.Make` functor with a custom key type `int * int`. It then shows how to create an empty map and add key-value pairs to it. ```ML module IntPairs = struct type t = int * int let compare (x0,y0) (x1,y1) = match Stdlib.compare x0 x1 with 0 -> Stdlib.compare y0 y1 | c -> c end module PairsMap = Map.Make(IntPairs) let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world") ``` -------------------------------- ### OCaml Hashtable Key Hashing Examples (Make.H) Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/MoreLabels/Hashtbl/Make/argument-1-H/index Illustrates common and suitable pairs of equality predicates and hashing functions for OCaml hashtable keys, as used by the `Make.H` parameter. These examples cover structural equality, structural equality with NaN handling, and physical equality. ```ocaml (* Comparing objects by structure (provided objects do not contain floats) *) ("(=)", hash) (* Comparing objects by structure and handling Stdlib.nan correctly *) ("(fun x y -> compare x y = 0)", hash) (* Comparing objects by physical equality (e.g. for mutable or cyclic objects) *) ("(==)", hash) ``` -------------------------------- ### Example: Temporary File Descriptor Management with at_exit Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Domain/index Demonstrates using `at_exit` to ensure a temporary file descriptor is closed upon domain exit. This pattern prevents resource leaks. ```ocaml let temp_file_key = Domain.DLS.new_key (fun _ -> let tmp = snd (Filename.open_temp_file "" "") in Domain.at_exit (fun () -> close_out_noerr tmp); tmp) ``` -------------------------------- ### Get Parser RHS Item Positions (OCaml) Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Parsing/index Retrieves the start and end positions (line and column) of a specific item on the right-hand side of a grammar rule. Similar to rhs_start and rhs_end, but returns Lexing.position for detailed location tracking. ```ocaml let rhs_start_pos: int => Lexing.position; let rhs_end_pos: int => Lexing.position; ``` -------------------------------- ### Create and Use Symbolic Output Buffer Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Format/index Demonstrates how to create a symbolic output buffer, obtain a formatter for it, and flush the buffer to retrieve symbolic output items. This is the fundamental workflow for symbolic pretty-printing. ```ocaml let sob = make_symbolic_output_buffer () let ppf = formatter_of_symbolic_output_buffer sob (* Use ppf for pretty-printing here... For example: Printf.fprintf ppf "Hello, %s!\n" "World" *) let items = flush_symbolic_output_buffer sob ``` -------------------------------- ### Min/Max Binding Operations in OCaml Source: https://melange.re/v5.0.0/api/re/melange/Js_parser/Flow_map/index Functions for retrieving and manipulating the minimum and maximum key-value pairs in the tree. This includes getting the minimum or maximum binding as a tuple or an option, removing the minimum binding, and converting the tree to an enumeration starting from the minimum. ```ocaml let cons_enum: t0('a, 'b) => enumeration('a, 'b) => enumeration('a, 'b); let min_binding: t0('a, 'b) => leaf_tuple('a, 'b); let min_binding_from_node_unsafe: t0('a, 'b) => leaf_tuple('a, 'b); let min_binding_opt: t0('a, 'b) => option(('a, 'b)); let max_binding: t0('a, 'b) => leaf_tuple('a, 'b); let max_binding_opt: t0('a, 'b) => option(('a, 'b)); let remove_min_binding_from_node_unsafe: t0('a, 'b) => t0('a, 'b); ``` -------------------------------- ### Get Parser Symbol Positions (OCaml) Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Parsing/index Retrieves the start and end positions (line and column) of the string matching the left-hand side of a grammar rule. These functions return Lexing.position objects, offering more detailed location information than simple offsets. ```ocaml let symbol_start_pos: unit => Lexing.position; let symbol_end_pos: unit => Lexing.position; ``` -------------------------------- ### Create and Use Domain-Local Storage Keys in OCaml Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Domain/DLS/index Demonstrates the creation of a new domain-local storage (DLS) key using `new_key` and its subsequent retrieval using `get`. It highlights the behavior of the initializer function, especially when `split_from_parent` is not provided, and the potential for the initializer to be called multiple times. ```ocaml let init () = "initial value" let key = Domain.DLS.new_key init let value = Domain.DLS.get key (* value will be "initial value" *) ``` -------------------------------- ### Get Parser Symbol Offsets (OCaml) Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Parsing/index Retrieves the start and end offsets of the string matching the left-hand side of a grammar rule within the input text. These functions should only be called within the action part of a grammar rule. The offsets are 0-based. ```ocaml let symbol_start: unit => int; let symbol_end: unit => int; ``` -------------------------------- ### Unsafe Get Value from Js.Dict Source: https://melange.re/v5.0.0/api/re/melange/Js/Dict/index Retrieves a value from a Js.Dict using its key without checking for key existence. This function returns an undefined value if the key is not present and should only be used when the key's existence is guaranteed, for example, after calling `Js_dict.keys`. ```reasonml let unsafeGet: t('a) => key => 'a; ``` ```reasonml Array.iter (fun key -> Js.log (Js_dict.unsafeGet dic key)) (Js_dict.keys dict) ``` -------------------------------- ### Hash Table Creation and Options Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Hashtbl/index This section details how to create a new hash table and the options available, such as initial size and randomization. ```APIDOC ## Generic interface `type t(!'a, !'b);` The type of hash tables from type `'a` to type `'b`. `let create: ?random:bool => int => t('a, 'b);` `Hashtbl.create n` creates a new, empty hash table, with initial size greater or equal to the suggested size `n`. For best results, `n` should be on the order of the expected number of elements that will be in the table. The table grows as needed, so `n` is just an initial guess. If `n` is very small or negative then it is disregarded and a small default size is used. The optional `~random` parameter (a boolean) controls whether the internal organization of the hash table is randomized at each execution of `Hashtbl.create` or deterministic over all executions. A hash table that is created with `~random` set to `false` uses a fixed hash function (`hash`) to distribute keys among buckets. As a consequence, collisions between keys happen deterministically. A hash table that is created with `~random` set to `true` uses the seeded hash function `seeded_hash` with a seed that is randomly chosen at hash table creation time. If no `~random` parameter is given, hash tables are created in non-random mode by default. This default can be changed either programmatically by calling `randomize` or by setting the `R` flag in the `OCAMLRUNPARAM` environment variable. ``` -------------------------------- ### Get Backtrace Slots - OCaml Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Printexc/index Retrieves the slots of a raw backtrace in a user-friendly format. Returns None if no useful information is found, for example, if modules are not compiled with debug information. The returned array's index 0 corresponds to the most recent call. ```ocaml let backtrace_slots: raw_backtrace => option(array(backtrace_slot)) ``` -------------------------------- ### Map Example: Creating and Populating a Map with Custom Key Type Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Map/index Demonstrates how to create a custom ordered type for key-value pairs and use the `Map.Make` functor to create a map module. The example shows adding elements to the map and illustrates the resulting type. ```ocaml module IntPairs = struct type t = int * int let compare (x0,y0) (x1,y1) = match Stdlib.compare x0 x1 with 0 -> Stdlib.compare y0 y1 | c -> c end module PairsMap = Map.Make(IntPairs) let m = PairsMap.(empty |> add (0,1) "hello" |> add (1,0) "world") ``` -------------------------------- ### Get Symbol and RHS Start/End Positions in Parsing Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Parsing/index Retrieves the starting and ending Lexing.position for grammar rule symbols or right-hand side items. These functions are useful for more detailed error reporting or source code analysis, providing line and column information. ```ocaml val symbol_start_pos : unit -> Lexing.position val symbol_end_pos : unit -> Lexing.position val rhs_start_pos : int -> Lexing.position val rhs_end_pos : int -> Lexing.position ``` -------------------------------- ### Get Start Offset of Lexeme in Input Stream (OCaml) Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Lexing/index Returns the offset in the input stream of the first character of the matched string. The input stream's first character has an offset of 0. It takes the lexbuf and returns an integer offset. ```OCaml let lexeme_start: lexbuf => int; Lexing.lexeme_start lexbuf ``` -------------------------------- ### Using StdLabels for Array Initialization Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/StdLabels/index Shows how to initialize a matrix using the labeled Array module. This example requires the StdLabels module to be opened. ```ocaml open StdLabels let everything = Array.create_matrix ~dimx:42 ~dimy:42 42 ``` -------------------------------- ### Get Symbol and RHS Start/End Offsets in Parsing Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Parsing/index Retrieves the starting and ending character offsets for grammar rule symbols or right-hand side items. These functions are intended for use within the action part of a grammar rule and assume 0-based indexing for characters. ```ocaml val symbol_start : unit -> int val symbol_end : unit -> int val rhs_start : int -> int val rhs_end : int -> int ``` -------------------------------- ### Configure File Watcher Source: https://melange.re/v5.0.0/api/re/melange/Node/Fs/Watch/index Sets up the configuration for the file watcher. Options include persistence, recursion, and encoding. If encoding is 'utf8', the filename will be a Buffer. ```reasonml let config: ?persistent:bool => ?recursive:bool => ?encoding:Js.String.t => unit => config; ``` -------------------------------- ### Get Parser RHS Item Offsets (OCaml) Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Parsing/index Retrieves the start and end offsets of a specific item on the right-hand side of a grammar rule. The 'n' parameter indicates the item's position (1-based) in the rule. These functions are useful for precisely locating parts of the parsed input. ```ocaml let rhs_start: int => int; let rhs_end: int => int; ``` -------------------------------- ### Basic Queue Operations in OCaml Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Queue/index Demonstrates the fundamental operations of the Stdlib.Queue module, including creating a queue, adding elements, checking its length, and removing elements until it's empty. It also shows the 'Empty' exception raised when attempting to remove an element from an empty queue. ```ocaml # let q = Queue.create () val q : '_weak1 Queue.t = # Queue.push 1 q; Queue.push 2 q; Queue.push 3 q - : unit = () # Queue.length q - : int = 3 # Queue.pop q - : int = 1 # Queue.pop q - : int = 2 # Queue.pop q - : int = 3 # Queue.pop q Exception: Stdlib.Queue.Empty. ``` -------------------------------- ### Extract Substring by Start and End Source: https://melange.re/v5.0.0/api/ml/melange/Js/String/index Extracts characters from a string starting at a specified index up to, but not including, an end index. Handles negative start indices by treating them as zero, returns an empty string if the end index is zero or negative, and swaps start and end if start is greater than end. ```ocaml substring ~start:3 ~end_:6 "playground" = "ygr";; substring ~start:6 ~end_:3 "playground" = "ygr";; substring ~start:4 ~end_:12 "playground" = "ground";; ``` -------------------------------- ### Buffer Creation and Initialization Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Buffer/index Functions for creating and initializing new buffer instances. ```APIDOC ## Buffer.create ### Description Creates a new, empty buffer with a specified initial size. ### Method N/A (Function call) ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ``` let b = Buffer.create 16 ``` ### Response #### Success Response (200) N/A (Returns a buffer of type `t`) #### Response Example N/A ``` -------------------------------- ### Creating and Managing Buffers with Stdlib.Buffer Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Buffer/index This snippet covers the creation and basic management of buffers using Stdlib.Buffer. It shows how to create a buffer with an initial size, retrieve its contents as a string or bytes, and get its current length. The `create` function allows specifying an initial capacity, and `contents` and `to_bytes` provide ways to access the buffer's data. ```ocaml (* Create a buffer with initial size 16 *) let b = Buffer.create 16 (* Get the current contents as a string *) let content_string = Buffer.contents b (* Get the current contents as bytes *) let content_bytes = Buffer.to_bytes b (* Get the current length of the buffer *) let len = Buffer.length b ``` -------------------------------- ### Check String Prefix Source: https://melange.re/v5.0.0/api/ml/melange/Js/String/index Checks if a string starts with a specified prefix at a given starting position. If the start position is negative, the search begins from the start of the string. Returns a boolean indicating whether the prefix is found. ```ocaml startsWith ~prefix:"Hello" ~start:0 "Hello, World!" = true;; startsWith ~prefix:"World" ~start:7 "Hello, World!" = true;; startsWith ~prefix:"World" ~start:8 "Hello, World!" = false;; ``` -------------------------------- ### Extract Substring by Start and Length Source: https://melange.re/v5.0.0/api/re/melange/Js/String Extracts a portion of a string based on a starting index and a desired length. Negative start indices are calculated from the end of the string. If the start index is out of bounds or length is non-positive, an empty string is returned. ```reasonml let substr: ?start:int => ?len:int => t => t; substr ~start:3 ~len:4 "abcdefghij" = "defghij" substr ~start:(-3) ~len:4 "abcdefghij" = "hij" substr ~start:12 ~len:2 "abcdefghij" = "" ``` -------------------------------- ### Memprof - Core Functionality Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Gc/Memprof/index This section covers the main functions for starting, stopping, and discarding memory profiles. ```APIDOC ## Memprof - Core Functionality ### `start` function Starts a memory profile with the given parameters. ### Method `let start: sampling_rate:float => ?callstack_size:int => tracker('minor, 'major) => t` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ocaml (* Example usage for starting a profile *) let my_tracker = { ... }; (* Define your tracker callbacks *) let profile = Gc.Memprof.start ~sampling_rate:0.001 ~callstack_size:64 my_tracker ``` ### Response #### Success Response (200) - **t** (type) - The profile identifier. #### Response Example None ### `stop` function Stops sampling for the current profile. ### Method `let stop: unit => unit` ### Parameters None ### Request Example ```ocaml Gc.Memprof.stop () ``` ### Response #### Success Response (200) Unit ### `discard` function Discards all profiling state for a stopped profile. ### Method `let discard: t => unit` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```ocaml (* Assuming 'profile' is a stopped Memprof profile identifier *) Gc.Memprof.discard profile ``` ### Response #### Success Response (200) Unit ``` -------------------------------- ### OCaml Hashtbl: Basic Hash Table Operations Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/MoreLabels/Hashtbl/index Demonstrates fundamental hash table operations including creation from a sequence, checking length, finding elements (with and without success), replacing elements, and observing changes in length. This showcases the basic API of OCaml's hash tables. ```ocaml (* 0...99 *) let seq = Seq.ints 0 |> Seq.take 100 (* build from Seq.t *) # let tbl = seq |> Seq.map (fun x -> x, string_of_int x) |> Hashtbl.of_seq val tbl : (int, string) Hashtbl.t = # Hashtbl.length tbl - : int = 100 # Hashtbl.find_opt tbl 32 - : string option = Some "32" # Hashtbl.find_opt tbl 166 - : string option = None # Hashtbl.replace tbl 166 "one six six" - : unit = () # Hashtbl.find_opt tbl 166 - : string option = Some "one six six" # Hashtbl.length tbl - : int = 101 ``` -------------------------------- ### Extract Substring by Start and End Index Source: https://melange.re/v5.0.0/api/re/melange/Js/String Extracts characters from a string starting at a given index up to (but not including) an end index. Negative start indices are treated as zero, and non-positive end indices result in an empty string. If start exceeds end, the indices are swapped. ```reasonml let substring: ?start:int => ?end_:int => t => t; substring ~start:3 ~end_:6 "playground" = "ygr";; substring ~start:6 ~end_:3 "playground" = "ygr";; substring ~start:4 ~end_:12 "playground" = "ground";; ``` -------------------------------- ### Example Usage of MoreLabels.Hashtbl Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/MoreLabels/index Demonstrates how to use the labeled version of Hashtbl.iter from the MoreLabels module. This approach requires opening the MoreLabels module to shadow the standard Hashtbl functions. The function 'g' is assumed to be defined elsewhere. ```ocaml open MoreLabels Hashtbl.iter ~f:(fun ~key ~data -> g key data) table ``` -------------------------------- ### Extract Substring by Start and Length Source: https://melange.re/v5.0.0/api/ml/melange/Js/String/index Extracts a substring from a given string based on a starting position and a desired length. Handles negative start positions by calculating from the end of the string and returns an empty string if the start position is out of bounds or the length is non-positive. Deprecated, refer to JavaScript String.prototype.substr. ```ocaml substr ~start:3 ~len:4 "abcdefghij" = "defghij" substr ~start:(-3) ~len:4 "abcdefghij" = "hij" substr ~start:12 ~len:2 "abcdefghij" = "" ``` -------------------------------- ### Generic Hashtable Creation from Sequence (OCaml) Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Hashtbl/index Shows how to build a generic hashtable from a sequence of key-value pairs using Hashtbl.of_seq. This is a common pattern for populating hashtables from iterable data structures. ```ocaml let seq = Seq.ints 0 |> Seq.take 100 let tbl = seq |> Seq.map (fun x -> x, string_of_int x) |> Hashtbl.of_seq ``` -------------------------------- ### Find character index from start (optional) - OCaml Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/String Safely finds the index of the first occurrence of a character in a string starting from a given position, returning an option. Raises Invalid_argument if the starting index is out of bounds. ```ocaml val index_from_opt : string -> int -> char -> int option index_from_opt s i c is the index of the first occurrence of `c` in `s` after position `i` (if any). * raises `Invalid_argument` if `i` is not a valid position in `s`. ``` -------------------------------- ### Create Integer Range Array - Belt.Array Source: https://melange.re/v5.0.0/api/ml/melange/Belt/Array/index Generates an array containing a sequence of integers starting from `start` and ending at `finish` (inclusive). If `start` is greater than `finish`, an empty array is returned. ```ocaml Belt.Array.range 0 3 = [|0;1;2;3|];; Belt.Array.range 3 0 = [||] ;; Belt.Array.range 3 3 = [|3|];; ``` -------------------------------- ### OCaml Pretty-Printer: Example of Max Indent and Margin Interaction Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Format/index Demonstrates the effect of `set_margin` and `set_max_indent` on pretty-printing output using `printf`. This example illustrates how nested boxes are handled when the maximum indentation limit is reached, leading to line breaks and specific formatting outcomes. ```ocaml set_margin 10; set_max_indent 5; printf "@[123456@[7@]89A@]@." (* yields 123456 789A *) printf "@[123456@[7@]89@]@." (* or printf "@[123@[456@[7@]89@]A@]@." *) ``` -------------------------------- ### Create Integer Range Array with Step - Belt.Array Source: https://melange.re/v5.0.0/api/ml/melange/Belt/Array/index Generates an array of integers starting from `start` up to `finish`, incrementing by `step`. Returns an empty array if `step` is zero or negative, or if `start` is greater than `finish`. ```ocaml Belt.Array.rangeBy 0 10 ~step:3 = [|0;3;6;9|];; Belt.Array.rangeBy 0 12 ~step:3 = [|0;3;6;9;12|];; Belt.Array.rangeBy 33 0 ~step:1 = [||];; Belt.Array.rangeBy 3 3 ~step:0 = [||] ;; ``` -------------------------------- ### Efficient String Concatenation with Stdlib.Buffer Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Buffer/index This example demonstrates how to efficiently concatenate a list of strings using Stdlib.Buffer. It initializes a buffer, adds each string from the list, and then retrieves the final concatenated string. This approach avoids the quadratic time complexity associated with pairwise string concatenation. ```ocaml let concat_strings ss = let b = Buffer.create 16 in List.iter (Buffer.add_string b) ss; Buffer.contents b ``` -------------------------------- ### Formatted Output with Continuations (kfprintf) Source: https://melange.re/v5.0.0/api/ml/melange/Stdlib/Printf/index The `kfprintf` function provides formatted output to a channel, but instead of returning directly, it passes the output channel to a continuation function upon completion. This allows for more control over resource management or subsequent actions after printing. ```ocaml val kfprintf : ('out_channel -> 'd) -> out_channel -> ('a, out_channel, unit, 'd) format4 -> 'a (* Same as fprintf, but instead of returning immediately, passes the out channel to its first argument at the end of printing. * since 3.09 *) ``` -------------------------------- ### Pretty-printing with Explicit Box Management Source: https://melange.re/v5.0.0/api/re/melange/Stdlib/Format/index Demonstrates basic pretty-printing by manually managing pretty-printing boxes. This involves opening a box, printing content using basic functions, and then closing the box. It's a more verbose but fundamental way to use the pretty-printing facility. ```ocaml Format.open_box 0; Format.print_string "x = "; Format.print_space (); Format.print_int 1; Format.close_box (); Format.print_newline () ``` -------------------------------- ### Check Installed Melange Version Source: https://melange.re/v5.0.0/how-to-guides A command to list installed packages matching 'melange' to verify the current version after an upgrade. ```bash opam list --installed melange ```