### OCaml Documentation and Build Tools Source: https://dev.realworldocaml.org/platform This example demonstrates the command-line usage for installing the odoc tool and building documentation for an OCaml project using dune. It shows how to generate HTML documentation locally. ```shell $ opam install odoc $ dune build @doc ``` -------------------------------- ### Query Installed OCaml Libraries Source: https://dev.realworldocaml.org/platform Lists all installed libraries in the current OCaml switch. This command is useful for checking available libraries and their versions before linking them into your project. ```bash ocamlfind list ``` -------------------------------- ### OCaml Autoformatting Setup with ocamlformat Source: https://dev.realworldocaml.org/platform This snippet illustrates the initial setup for autoformatting OCaml code using ocamlformat. It includes creating a configuration file to specify the tool version and installing the tool via opam. ```shell $ echo 'version=0.20.1' > .ocamlformat $ opam install ocamlformat.0.20.1 ``` -------------------------------- ### OCaml Platform: Hello World Project Setup Source: https://dev.realworldocaml.org/toc Guides through setting up a basic "Hello, World!" project using the OCaml platform. It covers opam local switch, compiler version selection, project structure, and building an executable. ```bash # 1. Create a new directory for the project mkdir hello_ocaml cd hello_ocaml # 2. Initialize opam local switch (optional, but recommended) opam switch create . 5.1.0 # Use your desired OCaml version # 3. Create Dune build system file cat < dune (executable (name hello) (libraries)) EOF # 4. Create the main OCaml source file cat < hello.ml let () = print_endline "Hello, OCaml World!" EOF # 5. Build the project dune build # 6. Run the executable _build/default/hello.exe ``` -------------------------------- ### Open Base Library in OCaml Source: https://dev.realworldocaml.org/guided-tour Opens the 'Base' library to make its definitions available without explicit referencing. This is a common setup step for many OCaml examples. ```ocaml open Base;; ``` -------------------------------- ### Install dune-release Source: https://dev.realworldocaml.org/platform Installs the `dune-release` tool, which automates the process of releasing OCaml projects to the Opam repository. This command-line instruction is used to add the tool to your OCaml environment. ```bash $ opam install dune-release ``` -------------------------------- ### Install OCaml Compiler and Libraries Source: https://dev.realworldocaml.org/install Installs a specific OCaml compiler version (4.13.1) and essential libraries like 'core', 'core_bench', and 'utop'. The `opam switch create` command downloads and installs the compiler, while `eval $(opam env)` updates the current shell's environment. Libraries are installed using `opam install`. ```Bash opam switch create 4.13.1 eval $(opam env) ``` ```Bash opam install core core_bench utop ``` -------------------------------- ### Install Project with Lock File (Opam) Source: https://dev.realworldocaml.org/platform Installs a project using a previously generated opam lock file. This allows users to reconstruct the exact opam environment used during the lock file's creation. ```shell opam install pkgname --locked opam switch create . --locked ``` -------------------------------- ### OCaml Project Structure Example Source: https://dev.realworldocaml.org/platform Illustrates a typical OCaml project directory structure, including build configuration files (`dune-project`, `dune`), package metadata (`.opam`), and source code organization (`lib`, `bin`, `test`). ```treeview . |-- dune-project |-- hello.opam |-- lib | |-- dune |-- bin | |-- dune | `-- main.ml `-- test |-- dune `-- hello.ml ``` -------------------------------- ### Start OCaml Toplevel Source: https://dev.realworldocaml.org/guided-tour Initiates the OCaml interactive toplevel environment from the command line. This environment allows for interactive evaluation of OCaml expressions. ```shell ocaml ``` -------------------------------- ### OCaml GitHub Action for CI Source: https://dev.realworldocaml.org/platform Configures a GitHub Actions workflow to build and test an OCaml project across multiple operating systems and OCaml compiler versions. It uses `actions/checkout@v2` to fetch code and `ocaml/setup-ocaml@v2` to set up the OCaml environment. Dependencies are installed using `opam`, and the project is built and tested with `dune`. ```yaml name: Hello world workflow on: pull_request: push: jobs: build: strategy: matrix: os: - macos-latest - ubuntu-latest - windows-latest ocaml-compiler: - 4.13.x runs-on: ${{ matrix.os }} steps: - name: Checkout code uses: actions/checkout@v2 - name: Use OCaml ${{ matrix.ocaml-compiler }} uses: ocaml/setup-ocaml@v2 with: ocaml-compiler: ${{ matrix.ocaml-compiler }} - run: opam install . --deps-only --with-test - run: opam exec -- dune build - run: opam exec -- dune runtest ``` -------------------------------- ### Install Vim OCaml Tools Source: https://dev.realworldocaml.org/install Installs essential tools for OCaml development in Vim, including 'user-setup' for general OCaml integration, 'merlin' for enhanced code analysis and completion, and 'ocamlformat' for code formatting. Running `opam user-setup install` applies the necessary configurations. ```Bash opam install user-setup merlin ocamlformat opam user-setup install ``` -------------------------------- ### Install Emacs OCaml Tools Source: https://dev.realworldocaml.org/install Installs Emacs-specific packages for OCaml development, including 'user-setup', 'tuareg' (for Emacs OCaml mode), 'ocamlformat' (for code formatting), and 'merlin' (for code completion and analysis). After installation, `opam user-setup install` applies the configurations. ```Bash opam install user-setup tuareg ocamlformat merlin opam user-setup install ``` -------------------------------- ### Install OCaml LSP Server Source: https://dev.realworldocaml.org/platform Command to install the OCaml Language Server Protocol (LSP) server using opam. This server is essential for IDE integration, providing features like auto-completion and definition search. ```bash opam install ocaml-lsp-server ``` -------------------------------- ### Initialize OCaml Project with Dune Source: https://dev.realworldocaml.org/platform Initializes a new OCaml project using the dune build system. This command creates a skeleton project structure with basic metadata, preparing it for development. It's a starting point for creating new OCaml applications or libraries. ```bash dune init proj hello Success: initialized project component named hello ``` -------------------------------- ### Installing and Opening Yojson Library in OCaml Source: https://dev.realworldocaml.org/json Instructions for installing the Yojson library using opam and opening it within the utop interactive environment. This is the initial setup for using Yojson in OCaml projects. ```ocaml open Core;; #require "yojson";; open Yojson;; ``` -------------------------------- ### OCaml: Example Usage of Running Sum Functions Source: https://dev.realworldocaml.org/guided-tour Demonstrates the practical application of `create` and `update` functions with a list of numbers. It shows how to initialize a `running_sum`, update it iteratively, and then compute the mean and standard deviation. ```OCaml let rsum = create ();; val rsum : running_sum = {sum = 0.; sum_sq = 0.; samples = 0} List.iter [1.;3.;2.;-7.;4.;5.] ~f:(fun x -> update rsum x);; - : unit = () mean rsum;; - : float = 1.33333333333333326 stdev rsum;; - : float = 3.94405318873307698 ``` -------------------------------- ### Example Usage: Running Search with Multiple Servers (Bash) Source: https://dev.realworldocaml.org/concurrent-programming This command demonstrates how to execute the OCaml search program with multiple servers specified. It shows how to pass server addresses as a comma-separated list and includes example search terms. This is a command-line execution example. ```Bash dune exec -- ./search.exe -servers localhost,api.duckduckgo.com "Concurrent Programming" "OCaml" ``` -------------------------------- ### Initialize opam Package Manager Source: https://dev.realworldocaml.org/install Initializes the opam package manager and configures the shell environment. It's recommended to say 'yes' when prompted to automatically adjust shell configuration files, including the PATH environment variable. This setup takes effect in new shell sessions. ```Bash opam init ``` ```Bash eval $(opam env) ``` -------------------------------- ### Complete OCaml MD5 Utility Example Source: https://dev.realworldocaml.org/command-line-parsing This is a complete OCaml code example for an MD5 utility. It defines a `do_hash` function, sets up a command-line interface with a summary and readme, and runs the command. ```ocaml open Core let do_hash file = Md5.digest_file_blocking file |> Md5.to_hex |> print_endline let command = Command.basic ~summary:"Generate an MD5 hash of the input data" ~readme:(fun () -> "More detailed information") Command.Param.( map (anon ("filename" %: string)) ~f:(fun filename () -> do_hash filename)) let () = Command_unix.run ~version:"1.0" ~build_info:"RWO" command ``` -------------------------------- ### OCaml Entry Point for Executable Source: https://dev.realworldocaml.org/platform Sets the entry point for an OCaml executable. This code modifies `bin/main.ml` to print a greeting from the `Hello.Msg` module. ```ocaml let () = print_endline Hello.Msg.greeting ``` -------------------------------- ### Install and Check atdgen Version Source: https://dev.realworldocaml.org/json Demonstrates how to install the `atdgen` executable using opam, a package manager for OCaml. It also shows how to verify the installed version of `atdgen`. ```Shell $ opam install atdgen $ atdgen -version 2.2.1 ``` -------------------------------- ### Configure Executable with Dune Source: https://dev.realworldocaml.org/platform Defines an executable program named 'hello' using the 'main' module and linking the 'hello' library. This configuration is placed in the `bin/dune` file. ```ocaml (executable (public_name hello) (name main) (libraries hello))) ``` -------------------------------- ### Running the Compiled OCaml Program Source: https://dev.realworldocaml.org/guided-tour This example demonstrates running the compiled OCaml executable 'sum.exe'. It shows how to pipe input numbers (one per line) to the program and the expected output after the program calculates the total. Ctrl-D is used to signal the end of input. ```bash $ ./_build/default/sum.exe 1 2 3 94.5 Total: 100.5 ``` -------------------------------- ### Construct OCaml Lists with :: Source: https://dev.realworldocaml.org/guided-tour Demonstrates constructing new OCaml lists by prepending elements to an existing list using the :: constructor. ```OCaml "French" :: "Spanish" :: languages;; ``` -------------------------------- ### Install Bash Completion Fragment Source: https://dev.realworldocaml.org/command-line-parsing This example shows how to generate a completion script for a command (cal_add_sub_days.native), save it to a file (cal.cmd), and then source it into the current bash shell. This enables tab completion for the command's arguments. ```bash $ env COMMAND_OUTPUT_INSTALLATION_BASH=1 ./cal_add_sub_days.native > cal.cmd $ . cal.cmd $ ./cal_add_sub_days.native add diff help version ``` -------------------------------- ### Execute Dune Build with Opam Environment Source: https://dev.realworldocaml.org/platform Executes the `dune build` command using `opam exec`. `opam exec` ensures that the command runs with the environment variables (like PATH) set by the active opam switch, allowing it to find locally installed tools and libraries. The `--` separates opam's arguments from the command's arguments. ```bash $ opam exec -- dune build ``` -------------------------------- ### Activate Opam Environment Variables Source: https://dev.realworldocaml.org/platform Evaluates the output of `opam env` to add the necessary directories (like bin, lib) from the current opam switch to the shell's PATH. This allows direct invocation of tools installed in the local switch without specifying their full path. ```bash $ eval $(opam env) ``` -------------------------------- ### OCaml: Directory Listing Query Handler Setup Source: https://dev.realworldocaml.org/first-class-modules Loads the necessary Core Unix library for file system operations. This is a prerequisite for the directory listing handler. ```ocaml #require "core_unix.sys_unix";; ``` -------------------------------- ### Example Usage of upcase_first_entry in OCaml Source: https://dev.realworldocaml.org/variables-and-functions Provides examples of calling the 'upcase_first_entry' function with different string inputs to demonstrate its behavior and expected output. ```ocaml upcase_first_entry "one,two,three";; - : string = "ONE,two,three" upcase_first_entry "";; - : string = "" ``` -------------------------------- ### OCaml Function Using Local Module Open (Syntax 2) Source: https://dev.realworldocaml.org/guided-tour Provides an alternative, more concise syntax for locally opening a module, applying it to the 'ratio' function. ```ocaml let ratio x y = Float.O.(of_int x / of_int y);; val ratio : int -> int -> float = ``` -------------------------------- ### Render Table Example Source: https://dev.realworldocaml.org/lists-and-patterns Shows an example of rendering a text table using OCaml's Stdio and a custom render_table function. It takes a list of headers and a list of rows as input. ```OCaml Stdio.print_endline (render_table ["language";"architect";"first release"] [ ["Lisp" ;"John McCarthy" ;"1958"] ; ["C" ;"Dennis Ritchie";"1969"] ; ["ML" ;"Robin Milner" ;"1973"] ; ["OCaml";"Xavier Leroy" ;"1996"] ]);; ``` -------------------------------- ### Search for OCaml Option Packages Source: https://dev.realworldocaml.org/platform Searches for available `ocaml-option` packages that can be used to customize OCaml compiler builds. This is useful for discovering available optimization flags and features. ```shell opam search ocaml-option ``` -------------------------------- ### Invalid Variable Naming in OCaml Source: https://dev.realworldocaml.org/guided-tour Provides examples of illegal variable names in OCaml, such as capitalized names, names starting with numbers, and names containing dashes, along with corresponding error messages. ```ocaml let Seven = 3 + 4;; Line 1, characters 5-10: Error: Unbound constructor Seven let 7x = 7;; Line 1, characters 5-7: Error: Unknown modifier 'x' for literal 7x let x-plus-y = x + y;; Line 1, characters 7-11: Error: Syntax error ``` -------------------------------- ### Bash: Example of Interactive Input with OCaml Program Source: https://dev.realworldocaml.org/command-line-parsing This Bash example demonstrates how to run the OCaml program that interactively prompts for input. It shows piping input to the program and the program's interactive prompt response. ```Bash echo 35 | dune exec -- ./cal.exe 2013-12-01 enter days: 2014-01-05 ``` -------------------------------- ### Variable Binding with Let in OCaml Source: https://dev.realworldocaml.org/guided-tour Demonstrates creating variables using the `let` keyword to store the results of expressions. Shows how to bind values and their types in the toplevel. ```ocaml let x = 3 + 4;; val x : int = 7 let y = x + x;; val y : int = 14 ``` -------------------------------- ### List Available OCaml Compilers Source: https://dev.realworldocaml.org/platform Lists available OCaml compiler versions that opam can use. This helps in choosing a specific version for a project or understanding compatibility. ```shell opam switch list-available ``` -------------------------------- ### Configure OCaml Toplevel (utop) Source: https://dev.realworldocaml.org/install Sets up the ~/.ocamlinit file to load the 'core.top' and 'ppx_jane' libraries and open the 'Base' standard library in the interactive toplevel (utop). This enhances the development environment by providing useful pretty-printers and syntax extensions. ```OCaml #require "core.top";; #require "ppx_jane";; open Base;; ``` -------------------------------- ### Using Deferred.map (>>|) as a shortcut for bind and return Source: https://dev.realworldocaml.org/concurrent-programming Introduces Deferred.map and its infix equivalent '>>|' as a more concise way to combine 'bind' and 'return'. This example rewrites 'count_lines' using this shortcut. ```ocaml #show Deferred.map;; val map : 'a Deferred.t -> f:('a -> 'b) -> 'b Deferred.t let count_lines filename = Reader.file_contents filename >>| fun text -> List.length (String.split text ~on:'\n');; val count_lines : string -> int Deferred.t = count_lines "/etc/hosts";; - : int = 10 ``` -------------------------------- ### Example Usage and Output Source: https://dev.realworldocaml.org/foreign-function-interface Demonstrates how to execute the compiled OCaml program with sample input and shows the expected sorted output. ```bash echo 2 4 1 3 | dune exec ./qsort.exe\n1 2 3 4 ``` -------------------------------- ### Running OCaml Executable Built with Dune Source: https://dev.realworldocaml.org/files-modules-and-programs Executes a compiled OCaml program located in the '_build/default' directory. This example pipes input from 'grep' to the executable. ```Bash grep -Eo '[[:alpha:]]+' freq.ml | ./_build/default/freq.exe ``` -------------------------------- ### Get Length of OCaml List Source: https://dev.realworldocaml.org/guided-tour Calculates the number of elements in an OCaml list using the List.length function from the Base module. ```OCaml List.length languages;; ``` -------------------------------- ### Example Usage of Anonymous Arguments (Bash) Source: https://dev.realworldocaml.org/command-line-parsing Demonstrates how to execute an OCaml program that parses sequences of arguments, showing sample command-line invocation and expected output. ```Bash dune exec -- ./md5.exe /etc/services ./_build/default/md5.exe MD5 (/etc/services) = 6501e9c7bf20b1dc56f015e341f79833 MD5 (./_build/default/md5.exe) = 6602408aa98478ba5617494f7460d3d9 ``` -------------------------------- ### Build and Execute OCaml Program Locally Source: https://dev.realworldocaml.org/platform Commands to build an OCaml project using `dune build` and then execute the program locally using `dune exec`. The output shows the successful execution of the 'Hello World' program. ```bash dune build dune exec -- bin/main.exe Hello World ``` -------------------------------- ### OCaml Compile-Time Type Error Example Source: https://dev.realworldocaml.org/guided-tour Demonstrates a compile-time error in OCaml where an operation expects an integer but receives a string, preventing the code from running. ```OCaml let add_potato x = x + "potato";; Line 2, characters 9-17: Error: This expression has type string but an expression was expected of type int ``` -------------------------------- ### OCaml Implementation of a Simulated Query Handler Source: https://dev.realworldocaml.org/first-class-modules Provides an example implementation of the 'Unique' query handler using the simulated types, demonstrating how to create and configure a handler instance. ```ocaml let unique_handler config_sexp = let config = Unique.config_of_sexp config_sexp in let unique = Unique.create config in { name = Unique.name; eval = (fun sexp -> Unique.eval unique sexp); };; val unique_handler : Sexp.t -> query_handler_instance = ``` -------------------------------- ### OCaml Runtime Exception Example (Division by Zero) Source: https://dev.realworldocaml.org/guided-tour Illustrates a runtime exception in OCaml caused by division by zero, which is not caught by the type system and occurs during execution. ```OCaml let is_a_multiple x y = x % y = 0;; val is_a_multiple : int -> int -> bool = is_a_multiple 8 2;; - : bool = true is_a_multiple 8 0;; Exception: Invalid_argument "8 % 0 in core_int.ml: modulus should be positive". ``` -------------------------------- ### Valid Variable Naming Conventions in OCaml Source: https://dev.realworldocaml.org/guided-tour Illustrates legal identifiers for OCaml variables, including those with numbers and underscores. Shows successful variable binding examples. ```ocaml let x7 = 3 + 4;; val x7 : int = 7 let x_plus_y = x + y;; val x_plus_y : int = 21 let x' = x + 1;; val x' : int = 8 ``` -------------------------------- ### Using first_if_true with integers in OCaml Source: https://dev.realworldocaml.org/guided-tour This example shows the `first_if_true` function used with integer arguments. A helper function `big_number` is defined to test integer values, further illustrating parametric polymorphism. ```ocaml let big_number x = x > 3;; val big_number : int -> bool = first_if_true big_number 4 3;; - : int = 4 ``` -------------------------------- ### Using first_if_true with strings in OCaml Source: https://dev.realworldocaml.org/guided-tour This example demonstrates the generic `first_if_true` function being used with string arguments. A helper function `long_string` is defined to test string lengths, showcasing parametric polymorphism. ```ocaml let long_string s = String.length s > 6;; val long_string : string -> bool = first_if_true long_string "short" "loooooong";; - : string = "loooooong" ``` -------------------------------- ### Building the OCaml Project with Dune Source: https://dev.realworldocaml.org/platform Initiates the build process for the OCaml project using the dune build system. This command also updates the project's opam file based on the defined metadata. ```bash $ dune build ``` -------------------------------- ### OCaml CLI Interaction with Query Handler Loader Source: https://dev.realworldocaml.org/first-class-modules Example of interacting with the OCaml query handler loader via its command-line interface, showing initial state and querying active services. ```shell dune exec -- ./query_handler_loader.exe >>> (loader known_services) (ls unique) >>> (loader active_services) (loader) ``` -------------------------------- ### OCaml: Simulating Mutable Variables with Refs (Basic) Source: https://dev.realworldocaml.org/guided-tour Illustrates the creation and modification of a single mutable value using the `ref` type. This example shows direct field access and modification of the `contents` field. ```OCaml let x = { contents = 0 };; val x : int ref = {contents = 0} x.contents <- x.contents + 1;; - : unit = () x;; - : int ref = {contents = 1} ``` -------------------------------- ### Get Dune Version from Local Switch Source: https://dev.realworldocaml.org/platform Executes the dune binary found within the local opam switch (`_opam/bin/dune`) to display its version. This confirms that the locally compiled dune is accessible and working correctly. ```bash ./_opam/bin/dune --version 3.0.2 ``` -------------------------------- ### List Test Artifacts in Build Directory Source: https://dev.realworldocaml.org/platform Lists the contents of the test build directory after running `dune runtest`. This shows the compiled executable (`hello.exe`) and related files generated by Dune. ```bash ls -la _build/default/test ``` -------------------------------- ### OCaml: Permuting an array using a for loop Source: https://dev.realworldocaml.org/guided-tour Example of an OCaml function that permutes an array in-place using a 'for' loop. It utilizes the 'Random' module for selecting elements to swap. Dependencies include the 'Array' and 'Random' modules. ```OCaml let permute array = let length = Array.length array in for i = 0 to length - 2 do (* pick a j to swap with *) let j = i + Random.int (length - i) in (* Swap i and j *) let tmp = array.(i) in array.(i) <- array.(j); array.(j) <- tmp done;; val permute : 'a array -> unit = ``` ```OCaml let ar = Array.init 20 ~f:(fun i -> i);; val ar : int array = [|0; 1; 2; 3; 4; 5; 6; 7; 8; 9; 10; 11; 12; 13; 14; 15; 16; 17; 18; 19|] permute ar;; - : unit = () ar;; - : int array = [|12; 16; 5; 13; 1; 6; 0; 7; 15; 19; 14; 4; 2; 11; 3; 8; 17; 9; 10; 18|] ``` -------------------------------- ### Automated Project Release (dune-release) Source: https://dev.realworldocaml.org/platform Initiates an interactive release process that includes running local tests, generating documentation, uploading to GitHub pages, and creating a pull request to the opam-repository. Requires GitHub authentication via a personal access token. ```shell dune-release ``` -------------------------------- ### Create OCaml Switch with System Compiler Source: https://dev.realworldocaml.org/platform Creates a new OCaml switch using the system's pre-installed OCaml compiler. This is the fastest method if the correct OCaml version is already present. ```shell $ opam switch create . 4.13.1 ``` -------------------------------- ### Connect to OCaml Async Server using Netcat Source: https://dev.realworldocaml.org/concurrent-programming Demonstrates how to connect to the running OCaml Async echo server using the `nc` (netcat) command. It shows how to launch the server and send messages through netcat, with the server echoing the input back. The `dune exec` command is used to build and run the OCaml executable. ```bash dune exec -- ./echo.exe & echo "This is an echo server" | nc 127.0.0.1 8765 This is an echo server echo "It repeats whatever I write" | nc 127.0.0.1 8765 It repeats whatever I write killall echo.exe ``` -------------------------------- ### OCaml Async: Example Echo Server Source: https://dev.realworldocaml.org/toc Illustrates the creation of a simple echo server using OCaml's Async library. It showcases how to handle client connections and send data back, demonstrating deferred chains. ```ocaml let handle_connection reader writer = let rec loop () = match%lwt Reader.read_line reader with | `Eof -> return () | `Ok line -> let%lwt () = Writer.write_line writer line in loop () in loop () let run_server () = let where = "127.0.0.1" in let port = 8080 in let%lwt listener = Tcp.( create_connection (where, port) >>= listener ) in let rec accept_connections () = let%lwt (client, host, port) = Listener.accept listener in don't_wait_for (handle_connection client (Tcp.Out.create client)); accept_connections () in accept_connections () ``` -------------------------------- ### Test Async responsiveness with threaded non-allocating loop (bytecode) Source: https://dev.realworldocaml.org/concurrent-programming This example tests the behavior of `log_delays` with a non-allocating busy loop executed in a separate thread using `In_thread.run`. In bytecode execution, this demonstrates that the timer process still gets to run because bytecode allows yielding during non-allocating loops, unlike native code. ```ocaml log_delays (fun () -> In_thread.run noalloc_busy_loop);; 32.186508178710938us, 116.56808853149414ms, 216.65477752685547ms, 316.83063507080078ms, 417.13213920593262ms, Finished at: 418.69187355041504ms, ``` -------------------------------- ### Dune Project Metadata Configuration Source: https://dev.realworldocaml.org/platform Configures essential project metadata including name, documentation URL, source repository, license, authors, maintainers, and enables automatic generation of opam files. ```scheme (name hello) (documentation "https://username.github.io/hello/") (source (github username/hello)) (license ISC) (authors "Your name") (maintainers "Your name") (generate_opam_files true) ``` -------------------------------- ### OCaml Bytecode Instructions Example Source: https://dev.realworldocaml.org/compiler-backend Shows a simplified textual representation of OCaml bytecode instructions for pattern matching. Demonstrates stack-based operations like 'acc', 'branch', 'const', 'return', 'closure', and 'makeblock'. ```text branch L2 L1: acc 0 branchifnot L3 const 101 return 1 L3: const 100 return 1 L2: closure L1, 0 push acc 0 makeblock 1, 0 pop 1 setglobal Pattern_monomorphic_small! ``` -------------------------------- ### View Opam Switches Source: https://dev.realworldocaml.org/platform Lists the available opam switches (sandboxed environments) on the system. It displays the switch name, the OCaml compiler version used in that switch, and a description. This helps in managing different development environments. ```bash opam switch # switch compiler description default ocaml.4.13.1 default ``` -------------------------------- ### OCaml: Examples of flexible_find with variant types Source: https://dev.realworldocaml.org/gadts Provides examples demonstrating the behavior of the `flexible_find` function when using different `If_not_found.t` constructors (`Return_none`, `Default_to`, `Raise`). These examples show how the function returns an `option` type in all cases. ```ocaml flexible_find ~f:(fun x -> x > 10) [1;2;5] Return_none;; - : int option = None flexible_find ~f:(fun x -> x > 10) [1;2;5] (Default_to 10);; - : int option = Some 10 flexible_find ~f:(fun x -> x > 10) [1;2;5] Raise;; Exception: (Failure "Element not found"). flexible_find ~f:(fun x -> x > 10) [1;2;20] Raise;; - : int option = Some 20 ``` -------------------------------- ### Install Ctypes and ctypes-foreign via opam Source: https://dev.realworldocaml.org/foreign-function-interface This command installs the necessary OCaml libraries, `ctypes` and `ctypes-foreign`, which are required for using the foreign function interface with C libraries. It assumes you have opam, the OCaml package manager, installed and configured. ```bash $ opam install ctypes ctypes-foreign ``` -------------------------------- ### Execute OCaml Program by Public Name Source: https://dev.realworldocaml.org/platform Demonstrates executing an OCaml program using its public name ('hello') via `dune exec`. This is a more convenient way to run the executable. ```bash dune exec -- hello Hello World ``` -------------------------------- ### Remove sequential duplicates from an OCaml list Source: https://dev.realworldocaml.org/guided-tour This OCaml function removes consecutive duplicate elements from a list. It handles the base case of an empty list and uses pattern matching for lists with at least two elements (`first :: second :: tl`). If adjacent elements are the same, it recursively calls itself with the tail starting from the second element; otherwise, it keeps the first element and processes the rest of the list. An improved version handles single-element lists explicitly. ```ocaml let rec remove_sequential_duplicates list = match list with | [] -> [] | [x] -> [x] | first :: second :: tl -> if first = second then remove_sequential_duplicates (second :: tl) else first :: remove_sequential_duplicates (second :: tl);; val remove_sequential_duplicates : int list -> int list = remove_sequential_duplicates [1;1;2;3;3;4;4;1;1;1];; - : int list = [1; 2; 3; 4; 1] ``` -------------------------------- ### Define OCaml Test Executable with Dune Source: https://dev.realworldocaml.org/platform Configures a test executable using a `dune` file. It specifies the library dependencies, in this case, the local 'hello' library, and sets the name of the test executable. This allows running tests with `dune runtest`. ```scheme (test (libraries hello) (name hello)) ``` -------------------------------- ### OCaml Example: Draggable Square Source: https://dev.realworldocaml.org/classes An example demonstrating how to create a draggable square by inheriting from the 'square' class and the 'draggable' mixin. ```ocaml class small_square = object inherit square 20 40 40 inherit draggable end ``` -------------------------------- ### List.init Function Type and Example in OCaml Source: https://dev.realworldocaml.org/imperative-programming Demonstrates the type signature of the List.init function and provides an example of its usage to create a list of strings. ```ocaml List.init;; - : int -> f:(int -> 'a) -> 'a list = ``` ```ocaml List.init 10 ~f:Int.to_string;; - : string list = ["0"; "1"; "2"; "3"; "4"; "5"; "6"; "7"; "8"; "9"] ``` -------------------------------- ### Executing OCaml Binary with Arguments Source: https://dev.realworldocaml.org/command-line-parsing These commands demonstrate how to build and execute an OCaml program using `dune exec`. They show how to query version and build information from the binary. ```bash dune exec -- ./md5.exe -version 1.0 dune exec -- ./md5.exe -build-info RWO ``` -------------------------------- ### Linting OCaml Project Metadata Source: https://dev.realworldocaml.org/platform Runs linting commands to check the consistency of OCaml project metadata. `opam dune-lint` verifies dune and opam file synchronization, while `opam lint` performs additional checks on opam files. ```bash $ opam dune-lint $ opam lint ``` -------------------------------- ### OCaml: List.find signature and examples Source: https://dev.realworldocaml.org/gadts Shows the type signature for `List.find` and provides examples of its usage with integers and characters, demonstrating how it returns an `option` type. ```ocaml List.find;; - : 'a list -> f:('a -> bool) -> 'a option = ``` ```ocaml List.find ~f:(fun x -> x > 3) [1;3;5;2];; - : int option = Some 5 List.find ~f:(Char.is_uppercase) ['a';'B';'C'];; - : char option = Some 'B' ``` -------------------------------- ### Initialize and Register Loader Handler (OCaml) Source: https://dev.realworldocaml.org/first-class-modules Demonstrates the final setup by creating a Loader instance with specific query handlers and then registering this loader instance itself as an active handler within the loader's system. ```OCaml let () = let loader = Loader.create [(module Unique); (module List_dir)] in let loader_instance = (module struct module Query_handler = Loader let this = loader end : Query_handler_instance) in Hashtbl.set loader.Loader.active ~key:Loader.name ~data:loader_instance; ``` -------------------------------- ### Dune Build File for Executable Source: https://dev.realworldocaml.org/guided-tour This `dune` file defines how to build an executable named 'sum'. It specifies that the build target is an executable and lists the required libraries ('base' and 'stdio') that the program depends on. ```dune (executable (name sum) (libraries base stdio)) ``` -------------------------------- ### OCaml Destructive Substitution Example with Make_interval Source: https://dev.realworldocaml.org/functors This example demonstrates destructive substitution by modifying the `Interval_intf` signature to replace the `endpoint` type with `int`. It shows the resulting signature for `Int_interval_intf`. ```OCaml module type Int_interval_intf = Interval_intf with type endpoint := int ``` ```OCaml module type Int_interval_intf = sig type t val create : int -> int -> t val is_empty : t -> bool val contains : t -> int -> bool val intersect : t -> t -> t end ``` -------------------------------- ### Create Git Tag for Release (dune-release) Source: https://dev.realworldocaml.org/platform Creates a local Git tag for the release by parsing the CHANGES.md file to determine the latest version. It prompts the user before creating the tag. ```shell dune-release tag ``` -------------------------------- ### OCaml Example: Animated Circle Source: https://dev.realworldocaml.org/classes An example of creating an animated circle that moves to the right for one second when clicked. It inherits from 'circle', 'animated', and uses an initializer to add the movement logic. ```ocaml class my_circle = object inherit circle 20 50 50 inherit animated Time.Span.second initializer updates <- [fun _ -> x <- x + 5] end ``` -------------------------------- ### OCaml printf example with timezone conversion Source: https://dev.realworldocaml.org/imperative-programming A practical example using printf to prompt the user for a timezone, find the corresponding Time_unix.Zone, and then print the current time in that timezone. It uses `%!` to flush the output buffer. ```ocaml open Core let () = printf "Pick a timezone: %!"; match In_channel.input_line In_channel.stdin with | None -> failwith "No timezone provided" | Some zone_string -> let zone = Time_unix.Zone.find_exn zone_string in let time_string = Time.to_string_abs (Time.now ()) ~zone in printf "The time in %s is %s.\n%!" (Time_unix.Zone.to_string zone) time_string ``` -------------------------------- ### C Main Entry Point for OCaml Embedding Source: https://dev.realworldocaml.org/compiler-backend A C program that serves as the main entry point for an application embedding OCaml bytecode. It includes necessary headers for OCaml interaction and calls the OCaml startup function. ```C #include #include #include #include #include int main (int argc, char **argv) { printf("Before calling OCaml\n"); fflush(stdout); caml_startup (argv); printf("After calling OCaml\n"); return 0; } ``` -------------------------------- ### Enabling ppx_let for monadic syntax Source: https://dev.realworldocaml.org/concurrent-programming Demonstrates how to enable the 'ppx_let' extension for OCaml, which allows for a more readable, special syntax for working with monads. ```ocaml #require "ppx_let";; ``` -------------------------------- ### OCaml Library Definition with Dune Source: https://dev.realworldocaml.org/compiler-frontend Defines an OCaml library named 'hello' with two modules, 'a' and 'b', and an executable 'test' that depends on the 'hello' library. This demonstrates a basic library and executable setup using Dune. ```dune (library (name hello) (modules a b)) (executable (name test) (libraries hello) (modules test)) ``` -------------------------------- ### OCaml Function to Get Value from Incomplete coption Source: https://dev.realworldocaml.org/gadts Provides a function 'get' that safely retrieves a value from an 'incomplete' coption, returning a default value if the coption is 'Absent'. It infers the 'incomplete' type. ```ocaml let get ~default o = match o with | Present x -> x | Absent -> default;; val get : default:'a -> ('a, incomplete) coption -> 'a = ``` -------------------------------- ### Menhir Grammar Start Symbol Declaration Source: https://dev.realworldocaml.org/parsing-with-ocamllex-and-menhir Declares the start symbol for the Menhir parser to be 'prog' and specifies that the parsed output should be of type 'Json.value option'. The '%%' signifies the end of the declaration section. ```menhir %start prog %% ``` -------------------------------- ### Parse service_info from String with Regex Source: https://dev.realworldocaml.org/records Parses a line from the '/etc/services' file into a 'service_info' record using OCaml's 're' library for regular expression matching. Requires the 're' library to be installed (`opam install re`). ```OCaml #require "re";; let service_info_of_string line = let matches = let pat = "([a-zA-Z]+)[ \t]+([0-9]+)/([a-zA-Z]+)" in Re.exec (Re.Posix.compile_pat pat) line in { service_name = Re.Group.get matches 1; port = Int.of_string (Re.Group.get matches 2); protocol = Re.Group.get matches 3; } ;; ``` -------------------------------- ### Create OCaml Switch with Compiler Variants and Options Source: https://dev.realworldocaml.org/platform Creates an OCaml switch with specific configuration options, such as the `flambda` optimizer, using `ocaml-variants` and `ocaml-option` packages. This allows for customized compiler builds. ```shell opam switch create . ocaml-variants.4.13.1+options ocaml-option-flambda ``` -------------------------------- ### Build and Run Benchmark (Dune/OCaml) Source: https://dev.realworldocaml.org/maps-and-hashtables This snippet shows how to build an executable using Dune and then run it with specific command-line arguments to measure the performance of map and hash table data structures. ```scheme dune build map_vs_hash2.exe ./_build/default/map_vs_hash2.exe -ascii -clear-columns time speedup ``` -------------------------------- ### OCaml: Examples of flexible_find with GADT Source: https://dev.realworldocaml.org/gadts Demonstrates the usage of the GADT-based `flexible_find` function. These examples highlight how the return type varies correctly: `Return_none` yields an `int option`, while `Default_to` and `Raise` return `int` directly. Exceptions are also shown. ```ocaml flexible_find ~f:(fun x -> x > 10) [1;2;5] Return_none;; - : int option = Base.Option.None flexible_find ~f:(fun x -> x > 10) [1;2;5] (Default_to 10);; - : int = 10 flexible_find ~f:(fun x -> x > 10) [1;2;5] Raise;; Exception: (Failure "No matching item found"). flexible_find ~f:(fun x -> x > 10) [1;2;20] Raise;; - : int = 20 ``` -------------------------------- ### Instantiate Query Handlers Using build_instance in OCaml Source: https://dev.realworldocaml.org/first-class-modules Demonstrates using the `build_instance` function to create instances for 'Unique' and 'List_dir' query handlers with their respective configurations. ```OCaml let unique_instance = build_instance (module Unique) 0;; let list_dir_instance = build_instance (module List_dir) "/var";; ``` -------------------------------- ### OCaml Expression Construction Examples Source: https://dev.realworldocaml.org/gadts Provides examples of constructing typed expressions using GADTs. It defines helper functions `i`, `b`, and `(+:)` for creating `int expr`, `bool expr`, and addition operations respectively. Type errors are shown when incompatible types are used. ```ocaml let i x = Value (Int x) and b x = Value (Bool x) and (+:) x y = Plus (x,y);; i 3 +: i 6;; i 3 +: b false;; ``` -------------------------------- ### OCaml CLI Loading and Unloading Query Handlers Source: https://dev.realworldocaml.org/first-class-modules Illustrates loading the 'ls' query handler with a configuration, using it, and then unloading it, showing its unavailability afterward. ```shell >>> (loader (load ls /var)) () >>> (ls .) (agentx at audit backups db empty folders jabberd lib log mail msgs named netboot pgsql_socket_alt root rpc run rwho spool tmp vm yp) >>> (loader (unload ls)) () >>> (ls .) Could not find matching handler: ls ``` -------------------------------- ### Generating OCamldoc Documentation Source: https://dev.realworldocaml.org/compiler-frontend Provides bash commands to generate HTML and UNIX manual pages from OCaml source code using the `ocamldoc` tool. It includes creating directories and running the documentation generation commands. ```bash $ mkdir -p html man/man3 $ ocamldoc -html -d html doc.ml $ ocamldoc -man -d man/man3 doc.ml $ man -M man Doc ``` -------------------------------- ### OCaml Failing Inline Test Example Source: https://dev.realworldocaml.org/testing An example of an OCaml inline test that is intentionally made to fail. The assertion `List.equal Int.equal (List.rev [ 3; 2; 1 ]) [ 3; 2; 1 ]` is false, causing the test runner to report a failure. ```ocaml open Base let%test "rev" = List.equal Int.equal (List.rev [ 3; 2; 1 ]) [ 3; 2; 1 ] ```